- Home /
Convert Texture2D to array of uint and back
For my game I need to convert a texture into an array of uint, do some manipulation, and then back to a texture. I came up with the following code, but it is rather slow.
private uint[] Texture2DToUIntArray(Texture2D texture)
{
Color32 c;
int width = texture.width;
int height = texture.height;
uint[] pixels = new uint[width * height];
for (int y = 0; y < height; y++)
{
for (int x = 0; x < width; x++)
{
c = texture.GetPixel(x, y);
pixels[y * width + x] = Color32ToUInt(c);
}
}
return pixels;
}
private Texture2D UIntArrayToTexture2D(uint[] pixels, int width, int height, TextureFormat format)
{
Color32 c;
Texture2D texture = new Texture2D(width, height, format, false);
for (int y = 0; y < height; y++)
{
for (int x = 0; x < width; x++)
{
c = UIntToColor32(pixels[y * width + x]);
texture.SetPixel(x, y, c);
}
}
texture.Apply();
return texture;
}
private uint Color32ToUInt(Color32 color)
{
return (uint)((color.a << 24) | (color.r << 16) | (color.g << 8) | (color.b << 0));
}
private Color32 UIntToColor32(uint color)
{
return new Color32((byte)(color >> 16), (byte)(color >> 8), (byte)(color >> 0), (byte)(color >> 24));
}
Is there any way to make these conversions faster?
Answer by quizcanners · Jul 27, 2015 at 04:59 PM
I am looking for this too, but you shouldn't use "SetPixel". Here is some pieces from my code, it mostly the same:
public uint[] pix;
public int w;
public void toColor (UnityEngine.Color32[] mpix){
for (int i=0; i<mpix.Length; i++){
mpix[i].r=(byte)(pix[i]);
mpix[i].g=(byte)(pix[i]>>8); //& 0xFF00);
mpix[i].b=(byte)(pix[i]>>16); //& 0xFF0000);
mpix[i].a=(byte)(pix[i]>>24); //& 0xFF000000);
}
}
public void fColor (UnityEngine.Color32[] mpix){
pix=new uint[mpix.Length];
for (int i=0; i<mpix.Length; i++) {
pix [i] = (uint)(mpix [i].r | (mpix [i].g << 8) | (mpix [i].b << 16) | (mpix [i].a << 24));
}
}
And to apply:
imgdta.MyTexture = new Texture2D (imgdta.wight,imgdta.wight, TextureFormat.RGBA32, false);
rend.material.mainTexture=imgdta.MyTexture;
imgdta.MyTexture.SetPixels3 (imgdta.MyPixels);
imgdta.MyTexture.Apply (false);
Answer by starlord89 · Oct 03, 2017 at 12:30 PM
I was wondering if you found a solution ? I tried your method and it crashes my unity after awhile
Your answer
Follow this Question
Related Questions
conversion between Color32[] and byte[] fast 1 Answer
Trying to convert a JC script to C # 2 Answers
Using an array instead 2 Answers
Rotate non square Color array by 90 degrees 1 Answer
Texture2D to RenderTexture 1 Answer