将图片从PictureBox上载到服务器

本文关键字:上载 服务器 PictureBox | 更新日期: 2023-09-27 18:29:56

我有一个pictureBox和form1上的一个按钮。单击该按钮时,应该会将文件上载到服务器。目前,我正在使用以下方法。首先在本地保存图像,然后上传到服务器:

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);

然后上传文件:

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);
}

我无法在StreamContent中使用位图类型。如何直接从pictureBox流式传输图像,而不是先将其保存为文件?

我使用MemoryStream编写了以下代码,但使用此方法上传的文件大小为0。为什么?

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);
}

将图片从PictureBox上载到服务器

我不确定这是否是正确的方法,但我已经通过创建一个新的流,然后将旧的流复制到其中来解决它:

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(....);