2010-11-01 52 views

回答

59

所述內置PictureBox.Load(string URL) Method 「設置ImageLocation到指定的URL,並顯示指示的圖像」。 (自.NetFramework 2)

+1

這看起來更簡單:)。 – 2010-11-01 16:50:38

+2

不幸的是,如果需要證書,人必須堅持另一種方法。 – Larry 2011-10-10 08:19:31

43

嘗試這種情況:

var request = WebRequest.Create("http://www.gravatar.com/avatar/6810d91caff032b202c50701dd3af745?d=identicon&r=PG"); 

using (var response = request.GetResponse()) 
using (var stream = response.GetResponseStream()) 
{ 
    pictureBox1.Image = Bitmap.FromStream(stream); 
} 
+2

這是一個非常有用的例子。 – 2013-07-18 14:29:34

+1

如果你想在後臺線程中下載圖像,這是一個更好的解決方案。謝謝! – YoniXw 2016-12-04 00:01:50

6
yourPictureBox.ImageLocation = "http://www.gravatar.com/avatar/6810d91caff032b202c50701dd3af745?d=identicon&r=PG" 
4

下面是我使用的解決方案。我不記得爲什麼我不能使用PictureBox.Load方法。我很確定這是因爲我想正確縮放&將下載的圖像放到PictureBox控件中。如果我記得,PictureBox上的所有縮放選項要麼拉伸圖像,要麼調整PictureBox的大小以適應圖像。我想要一個適當的縮放和中心圖像的大小我爲PictureBox設置。

現在,我只需要做出一個異步版本...

這裏是我的方法:

#region Image Utilities 

    /// <summary> 
    /// Loads an image from a URL into a Bitmap object. 
    /// Currently as written if there is an error during downloading of the image, no exception is thrown. 
    /// </summary> 
    /// <param name="url"></param> 
    /// <returns></returns> 
    public static Bitmap LoadPicture(string url) 
    { 
     System.Net.HttpWebRequest wreq; 
     System.Net.HttpWebResponse wresp; 
     Stream mystream; 
     Bitmap bmp; 

     bmp = null; 
     mystream = null; 
     wresp = null; 
     try 
     { 
      wreq = (System.Net.HttpWebRequest)System.Net.HttpWebRequest.Create(url); 
      wreq.AllowWriteStreamBuffering = true; 

      wresp = (System.Net.HttpWebResponse)wreq.GetResponse(); 

      if ((mystream = wresp.GetResponseStream()) != null) 
       bmp = new Bitmap(mystream); 
     } 
     catch 
     { 
      // Do nothing... 
     } 
     finally 
     { 
      if (mystream != null) 
       mystream.Close(); 

      if (wresp != null) 
       wresp.Close(); 
     } 

     return (bmp); 
    } 

    /// <summary> 
    /// Takes in an image, scales it maintaining the proper aspect ratio of the image such it fits in the PictureBox's canvas size and loads the image into picture box. 
    /// Has an optional param to center the image in the picture box if it's smaller then canvas size. 
    /// </summary> 
    /// <param name="image">The Image you want to load, see LoadPicture</param> 
    /// <param name="canvas">The canvas you want the picture to load into</param> 
    /// <param name="centerImage"></param> 
    /// <returns></returns> 

    public static Image ResizeImage(Image image, PictureBox canvas, bool centerImage) 
    { 
     if (image == null || canvas == null) 
     { 
      return null; 
     } 

     int canvasWidth = canvas.Size.Width; 
     int canvasHeight = canvas.Size.Height; 
     int originalWidth = image.Size.Width; 
     int originalHeight = image.Size.Height; 

     System.Drawing.Image thumbnail = 
      new Bitmap(canvasWidth, canvasHeight); // changed parm names 
     System.Drawing.Graphics graphic = 
        System.Drawing.Graphics.FromImage(thumbnail); 

     graphic.InterpolationMode = InterpolationMode.HighQualityBicubic; 
     graphic.SmoothingMode = SmoothingMode.HighQuality; 
     graphic.PixelOffsetMode = PixelOffsetMode.HighQuality; 
     graphic.CompositingQuality = CompositingQuality.HighQuality; 

     /* ------------------ new code --------------- */ 

     // Figure out the ratio 
     double ratioX = (double)canvasWidth/(double)originalWidth; 
     double ratioY = (double)canvasHeight/(double)originalHeight; 
     double ratio = ratioX < ratioY ? ratioX : ratioY; // use whichever multiplier is smaller 

     // now we can get the new height and width 
     int newHeight = Convert.ToInt32(originalHeight * ratio); 
     int newWidth = Convert.ToInt32(originalWidth * ratio); 

     // Now calculate the X,Y position of the upper-left corner 
     // (one of these will always be zero) 
     int posX = Convert.ToInt32((canvasWidth - (image.Width * ratio))/2); 
     int posY = Convert.ToInt32((canvasHeight - (image.Height * ratio))/2); 

     if (!centerImage) 
     { 
      posX = 0; 
      posY = 0; 
     } 
     graphic.Clear(Color.White); // white padding 
     graphic.DrawImage(image, posX, posY, newWidth, newHeight); 

     /* ------------- end new code ---------------- */ 

     System.Drawing.Imaging.ImageCodecInfo[] info = 
         ImageCodecInfo.GetImageEncoders(); 
     EncoderParameters encoderParameters; 
     encoderParameters = new EncoderParameters(1); 
     encoderParameters.Param[0] = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, 
         100L); 

     Stream s = new System.IO.MemoryStream(); 
     thumbnail.Save(s, info[1], 
          encoderParameters); 

     return Image.FromStream(s); 
    } 

    #endregion 

這裏的要求包括。 (有些人可能會被其他代碼是必要的,但包括所有爲了安全起見)

using System.Windows.Forms; 
using System.Drawing.Drawing2D; 
using System.IO; 
using System.Drawing.Imaging; 
using System.Text.RegularExpressions; 
using System.Drawing; 

如何我一般都用它:

ImageUtil.ResizeImage(ImageUtil.LoadPicture("http://someurl/img.jpg", pictureBox1, true); 
+1

你有很多資源在這裏,你沒有正確地處理,這是一個實用的方法,所以它可能會經常被調用:你應該添加適當的'使用(var ... ='或'.Dispose()'調用 - System.Drawing.Image,System.Drawing.Graphics,Bitmap和Stream都實現了IDisposable,因爲它們處理非託管資源,所以如果你沒有明確地釋放它們,它可能會在稍後回來咬你。 – stuartd 2013-08-15 22:06:52

相關問題