1. 程式人生 > >遠端獲取圖片二進位制流及儲存到本地

遠端獲取圖片二進位制流及儲存到本地

protected void Page_Load(object sender, EventArgs e)
{
  WebRequest myrequest = WebRequest.Create("http://xxxxx/userface.jpg");
  WebResponse myresponse = myrequest.GetResponse();
  Stream imgstream = myresponse.GetResponseStream();
  System.Drawing.Image img = System.Drawing.Image.FromStream(imgstream);
  //img.Save(Server.MapPath("test.jpg"),System.Drawing.Imaging.ImageFormat.Jpeg);
  MemoryStream ms = new MemoryStream();
  img.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
  Response.ClearContent(); //需要輸出圖象資訊 要修改HTTP頭 
  Response.ContentType = "image/gif";
  Response.BinaryWrite(ms.ToArray());
}
 WebRequest request = WebRequest.Create(uri);
                    WebResponse response = request.GetResponse();
                    if (response.ContentType.ToLower().Contains("image"))
                    {
                        using (Stream reader = response.GetResponseStream())
                        {
                            using (FileStream writer = new FileStream(path, FileMode.OpenOrCreate, FileAccess.Write))
                            {
                                byte[] buffer = new byte[512];
                                int c = 0;
                                while ((c = reader.Read(buffer, 0, buffer.Length)) > 0)
                                {
                                    writer.Write(buffer, 0, c);
                                    result = true;
                                }
                            }
                        }
                    }