- Home /
Why does my PNG texture color get distorted?
Hello Everyone,
I am having a strange issue while trying to render a png texture. I am creating the image.png by reading the screen pixels and applying them to a new texture. I save out the image as a png then read it back in using the WWW class.
Below is how I am reading in the screen:
// Create a texture the size of the screen, RGB24 format
int width = Screen.width;
int height = Screen.height;
Texture2D tex = new Texture2D (width, height, TextureFormat.RGB24, false);
// Read screen contents into the texture
tex.ReadPixels (new Rect(0, 0, width, height), 0, 0);
tex.Apply ();
// Encode texture into PNG
byte[] bytes = tex.EncodeToPNG();
Destroy (tex);
File.WriteAllBytes(dir + "/SavedScreen.png", bytes);
This code works fine and this is the image it saves out:
Here is my code for reading in the png:
public IEnumerator SetTexture(string screenShot, GameObject _go)
{
if(screenShot.Length != 0)
{
//Load in the file path
wwwBack = new WWW(screenShot);
Debug.Log ("www: Screen Texture not set! Time: " + Time.time.ToString ());
// wait until loaded
yield return wwwBack;
//create texture to catch from file
tex = new Texture2D(GridScript.imageWidth, GridScript.imageHeight, TextureFormat.DXT1, false);
// load texture
wwwBack.LoadImageIntoTexture(tex);
//set texture
BackgroundMat.mainTexture = (Texture)Instantiate(tex);
/*if(!isFull)
Destroy (_go);*/
if(!isFull)
{
StartCoroutine (DestroyGameObject (_go));
}
if(openList.Count == 0)
{
isFull = true;
}
screenShot = "";
Debug.Log ("www: Screen Texture set! Time: " + Time.time.ToString ());
wwwBack.Dispose ();
wwwBack = null;
}
}
This code works fine in reading in the image but when it is set it looks like this:
Any ideas as to why the color gets all messed up?
Thanks in advance!
What happens if you change the texture format on reading from DXT1 to RGB24?
Answer by Dracorat · Oct 31, 2013 at 04:24 PM
Something to be aware of:
http://docs.unity3d.com/Documentation/ScriptReference/WWW.LoadImageIntoTexture.html
This function replaces texture contents with downloaded image data, so texture size and format might change. JPG files are loaded into RGB24 format, PNG files are loaded into ARGB32 format. If texture format before calling LoadImage is DXT1 or DXT5, then the loaded image will be DXT-compressed (into DXT1 for JPG images and DXT5 for PNG images).
Is the output PNG file (I can't tell because your embedded image is actually a JPG) in this format already? Something might be lost if it has to be automatically converted.
Also, PNG is apparently supposed to be DXT5 - not DXT1.
Thank you so much Dracarat I just over looked the formats because I was rushing around and using JPG earlier in the program. So I had to change the format and compression type to complement PNG.
Thank you again!