Search code examples
c#pngbitmapimage-conversion

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


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.


Solution

  • 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);
    }