2013-01-18 24 views
2

我基本上是在Visual Studio 2010 .NET 4.0中開發一個軟件,在這裏我通過一臺PC捕獲屏幕截圖並通過網絡將其發送到另一臺。 由於我無法直接發送位圖,因此必須將其轉換爲字符串。 我做了很多互聯網搜索,但無法找到任何解決方案。 :(將位圖圖像轉換爲字符串格式以通過網絡(LAN)發送,反之亦然

我發現這個代碼在計算器本身。 但它不工作,我試圖打印(從圖像轉換)的字符串,但該計劃的行爲就像該行犯規存在。 我用了一個MessageBox.Show(字符串); 但是即使有一個味精框彈出 任何人都可以請幫我卡 Thankx提前:)(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 
+0

爲什麼它必須是一個字符串而不僅僅是一個字節緩衝區? –

+2

您可以使用基於文本的編碼發送它,但爲什麼不將圖像作爲二進制流發送? – gustavodidomenico

+0

實現這段代碼的任何地方,你是否給它一個你想要轉換的圖像的路徑? – cost

回答

4

嘗試將其轉換爲字節數組:

!?!
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; 
} 

我相信你可以簡單地將一個Bitmap對象轉換成一個Image對象。所以Image img = (Image)myBitmap; - 然後將其傳入上面的方法。

0

爲什麼它需要是一個字符串?你用什麼方法通過網絡發送?一個web服務?直接套接字?

不管如何你雖然發送它,最好的方法是將其轉換爲字節數組,然後傳遞數組通過網絡

如果你需要的是如何做到這一點,檢查一些代碼就像Sending and receiving an image over sockets with C#

0

你可以直接發送單個字節,但如果你真的想要一個字符串,你可以用base64的格式對它進行編碼。以下是此格式的encoding todecoding from的msdn文檔。你可以使用代碼@AdamPlocher在他的答案中發佈的圖像轉換爲一個字節數組(它使我省略了1 +)

相關問題