Easy way to convert a Bitmap and Png Image to text and vice versa

14,639

Solution 1

Based on @peters answer I've ended up using this:

string bitmapString = null;
using (MemoryStream memoryStream = new MemoryStream())
{
    image.Save(memoryStream, ImageFormat.Png); 
    byte[] bitmapBytes = memoryStream.GetBuffer();
    bitmapString = Convert.ToBase64String(bitmapBytes, Base64FormattingOptions.InsertLineBreaks);
}

and

Image img = null;
byte[] bitmapBytes = Convert.FromBase64String(pictureSourceString);
using (MemoryStream memoryStream = new MemoryStream(bitmapBytes))
{
    img = Image.FromStream(memoryStream);
}

Solution 2

From bitmap to string:

MemoryStream memoryStream = new MemoryStream();
bitmap.Save (memoryStream, ImageFormat.Png);
byte[] bitmapBytes = memoryStream.GetBuffer();
string bitmapString = Convert.ToBase64String(bitmapBytes, Base64FormattingOptions.InsertLineBreaks);

From string to image:

byte[] bitmapBytes = Convert.FromBase64String(bitmapString);
MemoryStream memoryStream = new MemoryStream(bitmapBytes);
Image image = Image.FromStream(memoryStream);
Share:
14,639
caesay
Author by

caesay

I'm in a committed relationship with good code, so if we go out it will only be as friends. Feel free to contact me by email at mk.stackexchange<a>caesay.com

Updated on June 05, 2022

Comments

  • caesay
    caesay almost 2 years

    what is the easiest way to translate a Bitmap & Png to string AND BACK AGAIN. Ive been trying to do some saves through memory streams and such but i cant seem to get it to work!

    Appearently i wasnt clear, what i want, is to be able to translate a Bitmap class, with an image in it.. into a system string. from there i want to be able to throw my string around for a bit, and then translate it back into a Bitmap to be displayed in a PictureBox.