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