cch
cch

Reputation: 27

How do I get an encoded image (png, jpg, etc) out of a Texture2D?

Below is the code I am trying to modify.

static byte[] GetImageAsByteArray(string imageFilePath)
{
    // Open a read-only file stream for the specified file.
    using (FileStream fileStream =
        new FileStream(imageFilePath, FileMode.Open, FileAccess.Read))
    {
        // Read the file's contents into a byte array.
        BinaryReader binaryReader = new BinaryReader(fileStream);
        return binaryReader.ReadBytes((int)fileStream.Length);
    }
}

As you can see this code uses a file path. I want to pass an image Texture2D into the method like below:

static byte[] GetImageAsByteArray(Texture2D image)

How do I get the same output as the filestream method but using texture2d. Below is my attempt at it:

static byte[] GetImageAsByteArray(Texture2D image)
{
    /* Open a read-only file stream for the specified file.
    using (FileStream fileStream =
        new FileStream(imageFilePath, FileMode.Open, FileAccess.Read))
        */
    {
        // Read the file's contents into a byte array.
        Debug.Log("MADE IT TO GETIMAGESBYTEARR");
       return binaryReader.ReadBytes(image.GetRawTextureData());

    }
}

Upvotes: 0

Views: 2449

Answers (1)

Ruzihm
Ruzihm

Reputation: 20249

Use an ImageConversion method depending on the encoding you want.

Texture2D image;    

// Encodes this texture into EXR format using ZIP compression
byte[] exrEncoded = ImageConversion.EncodeToEXR (image, Texture2D.EXRFlags.CompressZIP);

// Encodes this texture into JPG format
byte[] jpgEncoded = ImageConversion.EncodeToJPG (image);

// Encodes this texture into JPG format
byte[] pngEncoded = EncodeToPNG(image);

// Encodes this texture into TGA format
byte[] tgaEncoded = EncodeToTGA(image);

In order to use these, you must set the read/write enabled flag of the texture to true in the texture import settings.

Upvotes: 2

Related Questions