If you are creating images or altering them in real-time you may need to resize them at some point, so armed with Unity3d’s new GetPixelBilinear(float,float) function we can do a reasonable job of scaling an image at runtime. The function below “ScaleTexture” is written in c#, it takes 3 arguments and should be used as such:-
Returned Image(Texture 2d)= ScaleTexture(Source Image(Texture2D),Target Width(Int),Target Height(Int));
1 2 3 4 5 6 7 8 9 10 11 12 |
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=(1.0f / (float)targetWidth); float incY=(1.0f / (float)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; } |
76771 Total Views 7 Views Today
Awsome man, worked very nice! Thanks for sharing!
A very nice little function, I shall make use of this. Thanks!
Yep. Worked like a charm. Thanks.
Superb. Thank you so much
(A/B) * (C/D) = (AC)/(BD). Now we have :
float incX=((float)1 / source.width) * ((float)source.width/targetWidth);
this is equal to float incX = (1.0 / (float)targetWidth);
right ?
great helper function tho. THX
Absolutely, you are quite correct! I guess at the time I was going for the result, and my simple brain didn’t even think that through properly, always good to get clarity and optimisations, thank you.
Thanks!! It works beautifully.
Awesome!!! THX!! Works great! Could you explain me this lines?
for(int px=0; px<rpixels.Length; px++) {
rpixels[px] = source.GetPixelBilinear(incX*((float)px%targetWidth), incY*((float)Mathf.Floor(px/targetWidth)));
}
Hi Richard sorry real busy year, you probably have this by now, but for others it loops through all the pixels of the target texture, the px % width (modulus width) returns x pixel val and px / width returns the y value to be obtained, these values are multiplied (scaled) by the original source image dimensions / 1 to retrieve the correct bilinear co-ordinates from the source, the result pixel colour gets stored in the pixel array.
Thank you! it is perfect!