How to make Texture2D Readable via script

前端 未结 1 473
长情又很酷
长情又很酷 2020-11-29 10:59

I want to make user able to decode the QR image loaded from the gallery, I have found a plugin to explore and load the image as a texture2D, but to decode that QR code, the

相关标签:
1条回答
  • 2020-11-29 11:25

    There are two ways to do this:

    1.Use RenderTexture (Recommended):

    Use RenderTexture. Put the source Texture2D into RenderTexture with Graphics.Blit then use Texture2D.ReadPixels to read the image from RenderTexture into the new Texture2D.

    Texture2D duplicateTexture(Texture2D source)
    {
        RenderTexture renderTex = RenderTexture.GetTemporary(
                    source.width,
                    source.height,
                    0,
                    RenderTextureFormat.Default,
                    RenderTextureReadWrite.Linear);
    
        Graphics.Blit(source, renderTex);
        RenderTexture previous = RenderTexture.active;
        RenderTexture.active = renderTex;
        Texture2D readableText = new Texture2D(source.width, source.height);
        readableText.ReadPixels(new Rect(0, 0, renderTex.width, renderTex.height), 0, 0);
        readableText.Apply();
        RenderTexture.active = previous;
        RenderTexture.ReleaseTemporary(renderTex);
        return readableText;
    }
    

    Usage:

    Texture2D copy = duplicateTexture(sourceTextFromPlugin);
    

    This should work and should not throw any error.


    2.Use Texture2D.GetRawTextureData() + Texture2D.LoadRawTextureData():

    You can't use GetPixels32() because the Texture2D is not readable. You were so close about using GetRawTextureData().

    You failed when you used Texture2D.LoadImage() to load from GetRawTextureData().

    Texture2D.LoadImage() is only used to load PNG/JPG array bytes not Texture2D array byte.

    If you read with Texture2D.GetRawTextureData(), you must write with Texture2D.LoadRawTextureData() not Texture2D.LoadImage().

    Texture2D duplicateTexture(Texture2D source)
    {
        byte[] pix = source.GetRawTextureData();
        Texture2D readableText = new Texture2D(source.width, source.height, source.format, false);
        readableText.LoadRawTextureData(pix);
        readableText.Apply();
        return readableText;
    }
    

    There will be no error with the code above in the Editor but there should be an error in standalone build. Besides, it should still work even with the error in the standalone build. I think that error is more like a warning.

    I recommend you use method #1 to do this as it will not throw any error.

    0 讨论(0)
提交回复
热议问题