[英]Upload image to a server from PictureBox
我在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);
}
我不確定這是否是正確的方法,但我已經通過創建一個新的流然后將舊的流復制到它來解決它:
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.