3

我有一个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 类型。如何直接从图片框流式传输图像,而不是先将其保存为文件?

我使用 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);
}
4

2 回答 2

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
}
于 2013-09-01T15:51:12.553 回答
0
 Image returnImage = Image.FromStream(....);
于 2013-08-31T21:01:57.587 回答