Waltari
Waltari

Reputation: 1249

Texture2D to byte[] to String

I am having issues in turning Texture2D type image to bytes and then to string. When I do the following:

var myTextureBytes : byte[] = myTexture.EncodeToPNG();
Debug.Log(System.Text.Encoding.UTF8.GetString(myTextureBytes));

I just get a log output of "�PNG". Why is it so short? Whats the question mark? Shouldn't Unity be able to interpret UTF-8 chars? Also when I send that to my NodeJS server it says SyntaxError: Unexpected token and crashes the server.

Upvotes: 2

Views: 3431

Answers (2)

JeanLuc
JeanLuc

Reputation: 4903

the problem is that the bytes of PNG representation of the texture is not UTF-8 encoded, which is only for text.

To convert binary data to a string I would recommend base64 encoding.

var myTextureBytes : byte[] = myTexture.EncodeToPNG();
var myTextureBytesEncodedAsBase64 : String = System.Convert.ToBase64String(myTextureBytes);

Upvotes: 2

maraaaaaaaa
maraaaaaaaa

Reputation: 8163

have you tried using Default encoding?

Debug.Log(System.Text.Encoding.Default.GetString(myTextureBytes));

Upvotes: 0

Related Questions