views:

224

answers:

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.

+3  A: 

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
Isn't ImageFormat.Jpeg a lossy compression? Wouldn't ImageFormat.Png be a better choice due to its lossless nature?
Ants
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
+5  A: 

Based on @Peters answer (which contained some nasty syntax errors, and some code that can be optimized), I have come up with the correct solution to my problem:

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

and

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

Thanks peter! +1

Tommy