Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/302.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 使用WebClient将图像数据发送到服务器的最佳方式_C#_Winforms_Webclient - Fatal编程技术网

C# 使用WebClient将图像数据发送到服务器的最佳方式

C# 使用WebClient将图像数据发送到服务器的最佳方式,c#,winforms,webclient,C#,Winforms,Webclient,我正在使用Webclient尝试将winform应用程序上的图像发送到中央服务器。然而,我以前从未使用过WebClient,我很确定我所做的是错的 首先,我在表单上存储和显示我的图像,如下所示: _screenCap = new ScreenCapture(); _screenCap.OnUpdateStatus += _screen_CapOnUpdateStatus; capturedImage = imjObj; imagePreview.Image = capturedImage; 我

我正在使用Webclient尝试将winform应用程序上的图像发送到中央服务器。然而,我以前从未使用过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);
 }

我知道我应该把图像转换成一个字节[],但我不知道怎么做。有没有人能给我指出正确的方向,让我好好做这件事

您可以像这样转换为字节[]

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");
这可能会帮助你

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

参考。

您需要将
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));
}
可能重复的