2013-08-26 44 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)); 
} 
相关问题