How convert UI RawImage into byte array

5.5k views Asked by At

I am trying to convert a RawImage in a array bytes (bytes[]) but the RawImage don't have a encondePNG or something else to get a bytes for a RawImage, any idea how I can get the array of bytes?

public class RegistryScreen : UIScreen
{

Texture2D pickedImage;
public RawImage[] getRawImageProfile;

public void ChangeIconImage()
{        
    PickImageFromGallery();

    //WebService
    mygetImageProfileRequestData = new getImageProfileRequestData();

    //this is the problem 
    mygetImageProfileRequestData.image = getRawImageProfile[0].texture; 

}

public void PickImageFromGallery(int maxSize = 1024)
{
    NativeGallery.GetImageFromGallery((path) =>
    {
        if (path != null)
        {
            // Create Texture from selected image
            pickedImage = NativeGallery.LoadImageAtPath(path, maxSize);

            ////Sust. texture in image(Sprite)
            for (int i = 0; i < getRawImageProfile.Length; i++)
            {
                getRawImageProfile[i].texture = pickedImage;      
            }
        } 


        Debug.Log("getRawImage: " + getRawImageProfile[0].texture);            

    }, maxSize: maxSize);



}
1

There are 1 answers

4
Programmer On

RawImage is just a component rendering a Texture assigned to its texture property. To get the byte array, you need to access that Texture first then cast it to Texture2D.

Your RawImage component:

public RawImage rawImage;

Get the Texture it is rendering then cast it to Texture2D:

Texture2D rawImageTexture = (Texture2D)rawImage.texture;

Obtain the byte array as png or jpeg:

byte[] pngData = rawImageTexture.EncodeToPNG();
byte[] jpegData = rawImageTexture.EncodeToJPG();

If you want the uncompressed data of the RawImage:

Color32[] rawData = rawImageTexture.GetPixels32();

To also convert the the Color32[] to byte array see this post.