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

女生的网名这么多〃 提交于 2019-12-11 02:16:03

问题


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

回答1:


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.




回答2:


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#




回答3:


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



来源:https://stackoverflow.com/questions/14406342/convert-bitmap-image-to-string-format-to-send-over-networklan-and-vice-versa

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!