2

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.

Omar
  • 16,329
  • 10
  • 48
  • 66
caesay
  • 16,932
  • 15
  • 95
  • 160
  • 1
    By "translate to string," are you talking about encoding a la Base64, or OCRing text in the image? – itowlson Mar 03 '10 at 04:30
  • Is your need is to convert a _binary_ format to some _text_ of sorts (for example suitable for use in various internet protocols), or is it to OCR the text found in the images, or is it something else altogether ? – mjv Mar 03 '10 at 04:31
  • @itowlson, that makes two of us to be confused by the question ;-) – mjv Mar 03 '10 at 04:32
  • @mjv, itowlson: updated my question – caesay Mar 03 '10 at 04:38
  • 1
    Your updated question still doesn't answer mjv and itowlson's questions. Do you expect the bitmap to text conversion to do some kind of OCR? Or do you need to encode your bitmap data into some string format? – Ants Mar 03 '10 at 05:05

2 Answers2

8

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);
}
caesay
  • 16,932
  • 15
  • 95
  • 160
4

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);
Peter
  • 1,595
  • 13
  • 18
  • Isn't ImageFormat.Jpeg a lossy compression? Wouldn't ImageFormat.Png be a better choice due to its lossless nature? – Ants Mar 03 '10 at 05:26
  • I'm travelling, without a development environment, so answered from memory (my own) and some Googleing about the syntax. I didn't consider that Jpeg is lossy, but agree and will update my answer... – Peter Mar 03 '10 at 06:16