【问题标题】:How to get an image to a pictureBox from a URL? (Windows Mobile)如何从 URL 获取图片到图片框? (Windows 移动版)
【发布时间】:2022-02-24 01:17:20
【问题描述】:

在使用 Compact Framework 时,从 URL 获取图像的最佳方法是什么以及如何?

我发现的东西是这个(用它做了一个函数):

    public Bitmap getImageFromUrl()
    {
        HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(this.SImageUrl);
        request.Timeout = 5000; // 5 seconds in milliseconds
        request.ReadWriteTimeout = 20000; // allow up to 20 seconds to elapse
        HttpWebResponse response = (HttpWebResponse)request.GetResponse();
        Stream ms = response.GetResponseStream();
        Bitmap imageFromUrl;
        using (MemoryStream ms2 = new MemoryStream())
        {
            int bytes = 0;
            byte[] temp = new byte[4096];
            while ((bytes = ms.Read(temp, 0, temp.Length)) != 0)
                ms2.Write(temp, 0, bytes);
            imageFromUrl = new Bitmap(ms2);
        }

        return imageFromUrl;

    }

但它不会在图片框中显示任何图像。 有什么想法吗?

【问题讨论】:

  • 您是否使用调试器单步执行此代码?这至少可以说明哪条线路出现故障。
  • 我已经完成了它,但我看不到这些行中的任何一条都失败了。 HttpWebResponse“响应”显示 statuscode = ok (200),HttpWebResponse“响应”显示 contentLength = 11922,HttpWebResponse“响应”显示 ContentType = image/png,位图“imageFromUrl”显示 Size = 256、256 (正确),位图“imageFromUrl”显示 m_bmpdata = null,位图“imageFromUrl”显示 m_how = 1179689。
  • 哦...实际上... ms 抛出异常:'((System.Net.ContentLengthReadStream)ms).Length' 抛出类型为 'System.NotSupportedException' long {System.NotSupportedException }

标签: c# compact-framework


【解决方案1】:

我现在找到了更好的方法,但感谢史蒂夫丹纳的回答。 这是我的解决方案:

public Bitmap getImageFromURL(String sURL)
    {
        HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create(sURL);
        myRequest.Method = "GET";
        HttpWebResponse myResponse = (HttpWebResponse)myRequest.GetResponse();
        System.Drawing.Bitmap bmp = new System.Drawing.Bitmap(myResponse.GetResponseStream());
        myResponse.Close();

        return bmp;
    }

【讨论】:

  • 你说得对,这样更好。您正在削减那些其他内存流的所有开销。
【解决方案2】:

由于你有一个长度为 4096 的静态声明缓冲区,当它到达缓冲区的末尾时,这一行:

while ((bytes = ms.Read(temp, 0, temp.Length)) != 0)

正在尝试读取 4096 字节,而实际可能要少得多。把你的循环改成这样。

using (MemoryStream ms2 = new MemoryStream())
        {
            int bytes = 0;            
            while (true)
            {
               int byteLen = ms.Length - ms.Position >= 4096 ? 4096 : ms.Length -  ms.Position;
               byte[] temp = new byte[byteLen];
               bytes = ms.Read(temp, 0, byteLen);
               ms2.Write(temp, 0, bytes);
               imageFromUrl = new Bitmap(ms2);
               if (ms.Position == ms.Length) break;
        }

【讨论】:

    猜你喜欢
    • 2017-03-22
    • 2010-11-16
    • 2014-08-04
    • 2012-01-04
    • 1970-01-01
    • 2017-01-04
    • 2011-09-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多