【问题标题】:Upload image to a server from PictureBox从 PictureBox 将图像上传到服务器
【发布时间】:2023-03-30 02:53:01
【问题描述】:

我有一个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 中使用 Bitmap 类型。如何直接从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);
}

【问题讨论】:

  • 将图像保存到 MemoryStream,然后上传支持该 MemoryStream 的字节。
  • 让我查一下,谢谢
  • 很抱歉,我不知道如何在 MemoryStream 中保存 bmp。数据=新字节[bmp.NOTSURE]; m.Write(data, 0, data.Length);
  • 我可以上传,但上传的文件大小为 0。更新了我的问题

标签: c# .net winforms


【解决方案1】:

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

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
}

【讨论】:

    【解决方案2】:
     Image returnImage = Image.FromStream(....);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2022-09-26
      • 2011-02-02
      • 2015-03-29
      • 2011-10-15
      • 2020-11-19
      相关资源
      最近更新 更多