- Home /
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#.
Answer by kamgru123 · May 22, 2014 at 11:29 AM
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 :P
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);
Hi $$anonymous$$amgru, Thanks for your quick reply! Im getting this error message though.
"SerializationException: Type UnityEngine.Texture2D is not marked as Serializable."
Hi How did you solve the serialisation problem ?
The serialization problem can't be solved, because Texture2d can't be serialized by any .Net serialization method.
You should use EncodeToPng and Convert.ToBase64String just like the answer suggests. Base64 is just a way to encode any binary data as printable text.
Answer by BytesCrafter · Aug 09, 2016 at 09:01 AM
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 );
Your answer
Follow this Question
Related Questions
video media encoder addframe texture format 5 expected to be 4 1 Answer
Real-time Image Compression/Encoding on GPU 0 Answers
Image Based Reflection 0 Answers
Image in label + string..? 1 Answer
Problems with Russian characters within strings (C#) 3 Answers