- Home /
Crop Texture2D - Get/Set Pixels
Hello,
I'm working on a Crop system for my Texture2Ds, and I can't seem to get it to work, not sure what I'm doing wrong here:
//original image (before crop)
var oImg : Texture2D = fromQuad.material.mainTexture;
var pixels : Color[] = oImg.GetPixels(0, 0, oImg.width, oImg.height, 0);
//CROP IMAGE TO FIT SQUARE RATIO (cropSize)
var cropSize = 500;
var img : Texture2D = new Texture2D(cropSize, cropSize, TextureFormat.RGB24, false);
img.SetPixels(0, 0, cropSize, cropSize, pixels, 0);
img.Apply();
toQuad.material.mainTexture = img;
Any ideas? Thanks
FYI cropping code is RIGHT HERE:
http://docs.unity3d.com/ScriptReference/Texture2D.GetPixels.html
hooray!
Answer by Thomas-Mountainborn · Jul 01, 2015 at 05:32 PM
SetPixels() requires that the array is the correct size for the image (also keeping mip maps in mind). You are first getting the array of the original image in its original size, then you declare a new texture with a different resolution and you try to cram the same pixels in the new space. Instead, use oImg.GetPixels(0,0,cropSize, cropSize,0).
I was thinking about use that technique, but the only issue now is that it forces me to only crop the lower left portion of the image. Eventually, I want to use the centre of the image.
Then just offset with half of the remaining width and height: oImg.GetPixels((oImg.width - cropSize) / 2, (oImg.height - cropSize) / 2, cropSize, cropSize, 0);
Of course, this is only correct when oImg is larger than cropSize. For decent code you'd have to check that this is the case.
Also, I just remembered that you can use Graphics.DrawTexture() to do this operation in a single statement.
Answer by centsol · Apr 04, 2017 at 04:59 AM
Simple way of image Cropping in unity 5.5
public Texture2D mTexture;
void Start () {
Color[] c = mTexture.GetPixels (0, 0, 200, 200);
Texture2D m2Texture = new Texture2D (200, 200);
m2Texture.SetPixels (c);
m2Texture.Apply ();
gameObject.GetComponent<MeshRenderer> ().material.mainTexture = m2Texture;
}
Your answer
![](https://koobas.hobune.stream/wayback/20220613201616im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Resize Texture2D comes out grey 2 Answers
Unity 2D, Fit a texture/sprite to a specific shape/another sprite/polygon 0 Answers
Easy way to crop a Texture2D? 0 Answers
Crop Texture2D from center 2 Answers
Scaling / Resizing an Image (Texture2D) 6 Answers