Also, I’d rather crop the texture within the boundary of 256,256. But I cant find any functions in the documentation. If anyone has any insights on that as well.
As the docs say about Resize: “After resizing, texture pixels will be undefined.” It just resizes the texture, it does not scale the contents. You can use this instead.
Regarding Eric5h5’s famous and awesome TextureScale, here’s some example code that shows a use of it, and indeed how to crop.
For google: in Unity3D take a photo from your iPhone or Android webcam device camera, take a photo on to a WebCamTexture and then scale and crop the image and save to disk.
It’s all a piece of cake with TextureScale !!
public WebCamTexture wct;
public void UserClickedTakePhoto()
{
// take the photo. scale down to 256
// and crop to a central-square
// !!NOTE!! for simplicity this demo code
// assumes the tetxture is wider than high!
//consider... yield return new WaitForEndOfFrame();
Debug.Log("is " +wct.width +" h" +wct.height );
int oldW = wct.width; // assume it's wider than high
int oldH = wct.height;
Texture2D photo = new Texture2D(oldW, oldH,
TextureFormat.ARGB32, false);
photo.SetPixels( 0,0,oldW,oldH, wct.GetPixels() );
photo.Apply();
Debug.Log("took photo !");
Debug.Log("is " +photo.width +" h" +photo.height );
int newH = 256;
int newW = Mathf.FloorToInt(
((float)newH/(float)oldH) * oldW );
TextureScale.Bilinear(photo, newW,newH);
Debug.Log("scaled !");
Debug.Log("is " +photo.width +" h" +photo.height );
// finally crop to central square 256.256
int startAcross = (newW - 256)/2;
Debug.Log("starting across at: " +startAcross);
Color[] pix = photo.GetPixels(startAcross,0, 256,256);
photo = new Texture2D(256,256, TextureFormat.ARGB32, false);
photo.SetPixels(pix);
photo.Apply();
Debug.Log("'SetPixels' cropped !");
Debug.Log("is " +photo.width +" h" +photo.height );
demoImage.texture = photo;
// consider
// System.IO.File.WriteAllBytes(
// Application.persistentDataPath+"p.png",
// photo.EncodeToPNG());
// or
// byte[] bytes = photo.EncodeToPNG();
// File.WriteAllBytes(
// Application.persistentDataPath+"p.png", bytes);
}
Year in and year out, TextureScale is still the best and only way to scale your PNG and Texture2D in Unity3D! Hope it saves someone some typing.