Pregunta

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
¿Fue útil?

Solución

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.

Otros consejos

Why does it need to be a string? What method are you using to send it over the network? A webservice? Direct sockets?

Regardless of how you're sending it though, the best way would be to convert it to a byte array and then pass that array over the network

If you need some code of how to do this, check out similar questions on SO, like Sending and receiving an image over sockets with C#

You can directly send the individual bytes, but if you really want a string you can encode it in a format called base64. Here's the msdn documentation for encoding to and decoding from this format. You can convert the image to a byte array using the code @AdamPlocher posted in his answer (which I +1'ed as he saved me from doing it ;) )

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top