Resizing texture2d...

I’m using the screenshot script off the wiki which works fine for saving a screenshot, but I’m having trouble resizing it. (I know Texture2d.Resize loses the data so I’m trying to just save it to a new texture2d the size I want it)

I want to take a screenshot and resize it to 256x256 pixels. Actually, I want to take several screenshots, resize them and pack them into a single texture but I figured taking the screenshot and resizing it is the first step.

Texture2D texture = new Texture2D(Screen.width, Screen.height, TextureFormat.RGB24, false);
Texture2D textureSmall = new Texture2D(256, 256, TextureFormat.RGB24, false);

texture.ReadPixels(new Rect(0, 0, Screen.width, Screen.height), 0, 0);	
texture.Apply();
textureSmall.SetPixels (0,0,256,256,texture.GetPixels ());
textureSmall.Apply ();

byte[] bytes = texture.EncodeToPNG();
byte[] bytes2 = textureSmall.EncodeToPNG();		
      
	File.WriteAllBytes(Application.dataPath + "/../testscreennn-" + count + ".png", bytes2);
        File.WriteAllBytes(Application.dataPath + "/../testscreen-" + count + ".png", bytes);
        count++; 
 
        DestroyObject( texture );
 	DestroyObject( textureSmall );

I tried a few other things, like this function:

ScaleTexture(texture, 256, 256);

to call:

private Texture2D ScaleTexture(Texture2D source,int targetWidth,int targetHeight) {
    Texture2D result=new Texture2D(targetWidth,targetHeight,source.format,true);
    Color[] rpixels=result.GetPixels(0);
    float incX=((float)1/source.width)*((float)source.width/targetWidth);
    float incY=((float)1/source.height)*((float)source.height/targetHeight);
    for(int px=0; px<rpixels.Length; px++) {
    rpixels[px] = source.GetPixelBilinear(incX*((float)px%targetWidth),
    incY*((float)Mathf.Floor(px/targetWidth)));
    }
    result.SetPixels(rpixels,0);
    result.Apply();
    return result;
    }

With no success.

Any tips?

http://wiki.unity3d.com/index.php/TextureScale

–Eric

Thanks Eric, that works perfectly.

Nevermind, solved my other problem. Thanks again

You don’t save the rect array. PackTextures operates on a Texture2D, and the rect array is the UV coords.

I think you might need to read the docs again: “This function will replace current texture with the texture atlas. Size, format and whether the texture has mipmaps can change after packing. Resulting texture atlas will be as large as needed to fit all input textures, but only up to maximumAtlasSize in each dimension. If all input textures can’t fit into texture atlas of such size, they will be scaled down to fit.”

–Eric

Yeah I got it working thanks.

One question I have that I don’t see in search results is when I take the screenshots I have a bright pink background with an object, is there any way to remove the pink background while working with the byte code or between getpixel and setpixel, leaving a transparent background before outputting the png? By color? Alpha? Or ?