【问题标题】:Load an image from a url into a PictureBox将图像从 url 加载到 PictureBox
【发布时间】:2011-05-03 12:43:55
【问题描述】:

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

我该怎么做?

【问题讨论】:

  • 还有什么问题/疑问?

标签: c# .net image picturebox loadimage


【解决方案1】:

试试这个:

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】:

PictureBox.Load(string url) 方法“将 ImageLocation 设置为指定的 URL 并显示指定的图像。”

【讨论】:

  • 不幸的是,如果需要凭据,人们必须坚持另一种方法。
【解决方案3】:
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);
    

    【讨论】:

    • 您这里有很多资源没有正确处理,这是一种实用方法,因此它可能经常被调用:您应该添加适当的 using (var … = .Dispose() 调用 - System.Drawing.Image、System.Drawing.Graphics、Bitmap 和 Stream 都实现了 IDisposable,因为它们处理非托管资源,所以如果你不明确释放它们,它可能会在以后再次咬你。
    【解决方案5】:

    如果您尝试在 form_load 中加载图像,最好使用代码

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

    不仅从网络加载,而且在您的表单加载中也没有延迟。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-08-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-07-13
      • 1970-01-01
      相关资源
      最近更新 更多