从PictureBox上传图像到服务器

时间:2013-08-31 20:56:06

标签: c# .net winforms

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

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

2 个答案:

答案 0 :(得分: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
}

答案 1 :(得分:0)

 Image returnImage = Image.FromStream(....);