2013-08-26 43 views
2

我正在使用Webclient嘗試將我的圖像發送到中央服務器的winform應用程序。但是我從來沒有使用過WebClient,我很確定我在做什麼是錯誤的。使用WebClient將圖像數據發送到服務器的最佳方式

首先,我存儲和我的表單上顯示我的圖像,像這樣:

_screenCap = new ScreenCapture(); 
_screenCap.OnUpdateStatus += _screen_CapOnUpdateStatus; 
capturedImage = imjObj; 
imagePreview.Image = capturedImage; 

我已經成立了一個事件管理器時,我曾經採取截圖更新我imagePreview圖像。然後顯示它當過這樣的狀態變化:

private void _screen_CapOnUpdateStatus(object sender, ProgressEventArgs e) 
{ 
    imagePreview.Image = e.CapturedImage; 
} 

有了這個圖片我想將它傳遞給我的服務器,像這樣:

using (var wc = new WebClient()) 
{ 
    wc.UploadData("http://filelocation.com/uploadimage.html", "POST", imagePreview.Image); 
} 

我知道我應該將圖像轉換爲一字節[],但我不知道如何做到這一點。有人能請我指出正確的做法嗎?

+0

的可能重複的[如何圖像轉換在字節數組](http://stackoverflow.com/questions/3801275/how-to-convert-image-in-byte-array) – tafa

回答

2

你可以轉換爲byte []這樣

public byte[] imageToByteArray(System.Drawing.Image imageIn) 
{ 
    MemoryStream ms = new MemoryStream(); 
    imageIn.Save(ms,System.Drawing.Imaging.ImageFormat.Gif); 
    return ms.ToArray(); 
} 

,如果你有路徑的形象,你也可以做到這一點

byte[] bytes = File.ReadAllBytes("imagepath"); 
2

這可能會幫助你...

using(WebClient client = new WebClient()) 
{ 
    client.UploadFile(address, filePath); 
} 

this提到。

0

您需要將ContentType標頭設置爲image/gif或可能的binary/octet-stream的標頭,並在圖像上調用GetBytes()

using (var wc = new WebClient { UseDefaultCredentials = true }) 
{ 
    wc.Headers.Add(HttpRequestHeader.ContentType, "image/gif"); 
    //wc.Headers.Add("Content-Type", "binary/octet-stream"); 
    wc.UploadData("http://filelocation.com/uploadimage.html", 
     "POST", 
     Encoding.UTF8.GetBytes(imagePreview.Image)); 
} 
相關問題