Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice

Question Save Texture of RawImage after a new uvRect

Discussion in 'General Graphics' started by LimitlessMan, Sep 10, 2022.

  1. LimitlessMan

    LimitlessMan

    Joined:
    Jun 6, 2021
    Posts:
    5
    Hi,

    I want to save the texture of my RawImage but the result is inverted.
    I try to apply a uvRect to flip the image before saving and, I see to image flip on screen, but the image.jpg is still inverted. No mater what I do with the uvRect I see no change on image.jpg.

    There is my code :

    Code (CSharp):
    1.  
    2.  
    3.     Texture2D TextureToTexture2D(Texture texture)
    4.     {
    5.         Texture2D texture2D = new Texture2D(texture.width, texture.height, TextureFormat.RGBA32, false);
    6.         RenderTexture currentRT = RenderTexture.active;
    7.         RenderTexture renderTexture = RenderTexture.GetTemporary(texture.width, texture.height, 32);
    8.  
    9.         Graphics.Blit(texture, renderTexture);
    10.  
    11.         RenderTexture.active = renderTexture;
    12.  
    13.         texture2D.ReadPixels(new Rect(0, 0, renderTexture.width, renderTexture.height), 0, 0);
    14.         texture2D.Apply();
    15.  
    16.         //texture2D = FlipTexture(texture2D);
    17.  
    18.         RenderTexture.active = currentRT;
    19.         RenderTexture.ReleaseTemporary(renderTexture);
    20.  
    21.         return texture2D;
    22.     }
    23.  
    24.     myRawImage.uvRect = new Rect(myRawImage.uvRect.x, myRawImage.uvRect.y, myRawImage.uvRect.width, -myRawImage.uvRect.height);
    25.     Texture2D textureToSave = TextureToTexture2D(myRawImage.texture);
    26.     byte[] bytes = textureToSave.EncodeToJPG();
    27.     System.IO.File.WriteAllBytes(@"C:\Test\" + "Image_JPG.jpg", bytes);
    28.     break;
     
  2. LimitlessMan

    LimitlessMan

    Joined:
    Jun 6, 2021
    Posts:
    5
    It's ok I find an other way.

    No more need of uvRect and
    I add this function :


    void FlipTexture(ref Texture2D texture)
    {
    int textureWidth = texture.width;
    int textureHeight = texture.height;

    Color32[] pixels = texture.GetPixels32();

    for (int y = 0; y < textureHeight; y++)
    {
    int yo = y * textureWidth;
    for (int il = yo, ir = yo + textureWidth - 1; il < ir; il++, ir--)
    {
    Color32 col = pixels[il];
    pixels[il] = pixels[ir];
    pixels[ir] = col;
    }
    }
    texture.SetPixels32(pixels);
    texture.Apply();
    }