How to encode an image to a base64 string?

How do I go about encoding an image to base64? I would like to store images in a database using this method.

I have successfully converted a base64 string to an image and am using it in my project. Most of the information I have found works with strings. Like the following example.

byte[] bytesToEncode = Encoding.UTF8.GetBytes (inputText);
string encodedText = Convert.ToBase64String (bytesToEncode);

This is simple enough, but what do I do with an image?

This is how I am loading my image.

byte[] b64_bytes = System.Convert.FromBase64String(b64_string); 
tex = new Texture2D(1,1);
tex.LoadImage(b64_bytes);

Any help will be hugely appreciated.

Thank You
Oh, I am working in C#.

EDIT: Apparently you can’t serialize Texture2D (which I didn’t know). But there’s an easier solution: Texture2D.EncodeToPng() which returns byte array.

Texture2D mytexture;
byte[] bytes;

bytes = mytexture.EncodeToPng();

The following text is wrong. Don’t use it :stuck_out_tongue:


You could use BinaryFormatter to serialize it to bytes and then encode it.

using System.Runtime.Serialization.Formatters.Binary;


byte[] bytes;

using (MemoryStream ms = new MemoryStream())
{
    BinaryFormatter bf = new BinaryFormatter();
    bf.Serialize(ms, tex);
    bytes = ms.ToArray();
}

string enc = Convert.ToBase64String(bytes);

public RawImage prevUserPhoto = ; This must be not null! Put a texture wd here!
public RawImage newUserPhoto = ; Leave this null. This is where decoded texture go.

ToLoad Image saved on PlayerPrefs as “string”

Texture2D newPhoto = new Texture2D (1, 1);
newPhoto.LoadImage(Convert.FromBase64String(PlayerPrefs.GetString(“PhotoSaved”)));
newPhoto.Apply ();
newUserPhoto = newPhoto;

ToSave Image from a Texture 2D which must be a “readable” and RGBA 32 format.

string stringData = Convert.ToBase64String (prevUserPhoto .EncodeToJPG ()); //1
PlayerPrefs.SetString(PhotoSaved, stringData );

@Richard 3