代码之家  ›  专栏  ›  技术社区  ›  Vishnu Pradeep

将图像从url加载到PictureBox中

  •  37
  • Vishnu Pradeep  · 技术社区  · 14 年前

    我想将图像加载到 PictureBox . 这是我要加载的图像: http://www.gravatar.com/avatar/6810d91caff032b202c50701dd3af745?d=identicon&r=PG

    5 回复  |  直到 13 年前
        1
  •  70
  •   stuartd saeed    14 年前

    内在的 PictureBox.Load(string URL) Method “将ImageLocation设置为指定的URL并显示指示的图像。”(Since.NetFramework 2)

        2
  •  50
  •   Pieter van Ginkel    14 年前

    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);
    }
    
        3
  •  9
  •   BrandNewDev    13 年前
    yourPictureBox.ImageLocation = "http://www.gravatar.com/avatar/6810d91caff032b202c50701dd3af745?d=identicon&r=PG"
    
        4
  •  7
  •   blak3r    12 年前

    这是我使用的解决方案。我不记得为什么我不能使用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);
    
        5
  •  3
  •   Saghachi    6 年前

    如果您试图在表单加载时加载图像,最好使用代码

    pictureBox1.LoadAsync(@"http://google.com/test.png");