[英]Upload image to a server from PictureBox
I have one pictureBox and a button on form1 one. 我在form1上有一个pictureBox和一个按钮。 When the button is clicked, it should upload the file to the server.
单击该按钮时,应将该文件上载到服务器。 For now I am using the below method.
现在我使用以下方法。 First save the image locally and then upload to the server:
首先在本地保存图像,然后上传到服务器:
Bitmap bmp = new Bitmap(this.form1.pictureBox1.Width, this.form1.pictureBox1.Height);
Graphics g = Graphics.FromImage(bmp);
Rectangle rect = this.form1.pictureBox1.RectangleToScreen(this.form1.pictureBox1.ClientRectangle);
g.CopyFromScreen(rect.Location, Point.Empty, this.form1.pictureBox1.Size);
g.Dispose();
bmp.Save("filename", ImageFormat.Jpeg);
And then uploading that file: 然后上传该文件:
using (var f = System.IO.File.OpenRead(@"F:\filename.jpg"))
{
HttpClient client = new HttpClient();
var content = new StreamContent(f);
var mpcontent = new MultipartFormDataContent();
content.Headers.ContentType = new MediaTypeHeaderValue("image/jpeg");
mpcontent.Add(content);
client.PostAsync("http://domain.com/upload.php", mpcontent);
}
I can't use the Bitmap type in StreamContent. 我不能在StreamContent中使用Bitmap类型。 How can I stream the image from pictureBox directly instead saving it as file first?
如何直接从pictureBox流式传输图像而不是先将其保存为文件?
I came up with the below code using MemoryStream, but the uploaded file size is 0 using this method. 我使用MemoryStream想出了下面的代码,但使用此方法上传的文件大小为0。 Why?
为什么?
byte[] data;
using (MemoryStream m = new MemoryStream())
{
bmp.Save(m, ImageFormat.Png);
m.ToArray();
data = new byte[m.Length];
m.Write(data, 0, data.Length);
HttpClient client = new HttpClient();
var content = new StreamContent(m);
var mpcontent = new MultipartFormDataContent();
content.Headers.ContentType = new MediaTypeHeaderValue("image/png");
mpcontent.Add(content, "file", filename + ".png");
HttpResponseMessage response = await client.PostAsync("http://domain.com/upload.php", mpcontent);
//response.EnsureSuccessStatusCode();
string body = await response.Content.ReadAsStringAsync();
MessageBox.Show(body);
}
I am not sure if it is the correct way to do it, but I have solved it by creating a new stream and then copying the older one to it: 我不确定这是否是正确的方法,但我已经通过创建一个新的流然后将旧的流复制到它来解决它:
using (MemoryStream m = new MemoryStream())
{
m.Position = 0;
bmp.Save(m, ImageFormat.Png);
bmp.Dispose();
data = m.ToArray();
MemoryStream ms = new MemoryStream(data);
// Upload ms
}
Image returnImage = Image.FromStream(....);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.