How to get an image to a pictureBox from an URL? (Windows Mobile)

↘锁芯ラ 提交于 2019-12-07 08:39:13

问题


What and how is the best way to get an image from an URL when using the Compact Framework?

I have googled around, but could not find any decent answers.

Something i found was this (made a function out of it):

    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;

    }

But it won't show any images in the pictureBox. Any ideas?

Thanks i advance


回答1:


I now found something that works better, but thanks for an answer Steve Danner. Here is my solution:

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:


Since you have a statically declared buffer of length 4096, when it gets to the end of the buffer, this line:

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

is trying to read in 4096 bytes, when there are probably substantially less. Change your loop to something like this.

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;
        }


来源:https://stackoverflow.com/questions/2396288/how-to-get-an-image-to-a-picturebox-from-an-url-windows-mobile

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!