Search code examples
c#.net-remotingremoteobject

Convert Bitmap image to String format to send over network(LAN) and vice-versa


I am basically developing a software in Visual Studio 2010 .NET 4.0 where in I capture the screenshot from a pc and send it over a network to another. Since I cannot directly send a Bitmap, I have to convert it to String. I did a lot of internet search but cant find any solution. :(

I found this code on stackoverflow itself. But it it doesnt work. I tried to print the string (converted from image) but the program behaves like that line doesnt exist. I used a MessageBox.Show(String); But not even a msg box pops up! Can anyone please help? I'm stuck! Thankx in advance :) (Y)

bitmapString = null;       // Conversion from image to string
MemoryStream memoryStream = new MemoryStream();
bmpScreenshot.Save(memoryStream, ImageFormat.Png);
byte[] bitmapBytes = memoryStream.GetBuffer();
bitmapString = Convert.ToBase64String(bitmapBytes,Base64FormattingOptions.InsertLineBreaks); // Conversion from image to string end

Image img = null;                           //Conversion from string to image
byte[] bitmapBytes = Convert.FromBase64String(rob);
MemoryStream memoryStream = new MemoryStream(bitmapBytes);
img = Image.FromStream(memoryStream);   //Conversion from string to image end

Solution

  • Try to convert it to a byte array:

    public static byte[] ImageToByteArray(Image img)
    {
        byte[] byteArray = new byte[0];
        using (MemoryStream stream = new MemoryStream())
        {
            img.Save(stream, System.Drawing.Imaging.ImageFormat.Png);
            stream.Close();
    
            byteArray = stream.ToArray();
        }
        return byteArray;
    }
    

    I believe you can simply cast a Bitmap object to an Image object. So Image img = (Image)myBitmap; - then pass that into the method above.