简体   繁体   English

从URL获取图像,但未完全加载

[英]Get an Image from a URL but it is not loaded completely

I'm trying to get an image from an URL but when I save it to a file it is half of the actual image! 我正在尝试从URL获取图像,但是当我将其保存到文件中时,它只是实际图像的一半! I have searched many sites and solutions like HttpWebRequest.BeginGetResponse because I thought it is because I must buffer the data but it did not work. 我搜索了许多站点和解决方案,例如HttpWebRequest.BeginGetResponse,因为我认为这是因为我必须缓冲数据,但它无法正常工作。 I don't know which part of my code is wrong and making this problem!:( 我不知道我的代码的哪一部分是错误的并且造成了这个问题!

This is the code which retrieve image from URL: 这是从URL检索图像的代码:

 public static Bitmap GetImageFromUrl(string url)
    {
        string RefererUrl = string.Empty;
        int TimeoutMs = 22 * 1000;
        string requestAccept = "*/*";
        string UserAgent = "Mozilla/5.0 (Windows; U; Windows NT 6.0; en-US; rv:1.9.1.7) Gecko/20091221 Firefox/3.5.7";

        Bitmap img = null;
        HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);

        request.UserAgent = UserAgent;
        request.Timeout = TimeoutMs;
        request.ReadWriteTimeout = TimeoutMs * 6;
        request.Accept = requestAccept;

        if (!string.IsNullOrEmpty(RefererUrl))
        {
            request.Referer = RefererUrl;
        }

        try
        {
            WebResponse wResponse = request.GetResponse();
            using (HttpWebResponse response = wResponse as HttpWebResponse)
            {
                Stream responseStream = response.GetResponseStream();
                img = new Bitmap(responseStream);
                response.Close();
            }
        }
        catch (Exception)
        {
        }
        return img;
    }

This the code which saves the image in File: 这是将图像保存在File中的代码:

        byte[] imgBytes = tile.Image;
        using (MemoryStream ms = new MemoryStream(imgBytes))
        {
            using (Image img = Image.FromStream(ms))
            {
                ms.Dispose();
                Bitmap tempBmp = new Bitmap(img);
                img.Dispose();

                string activeDir = Environment.CurrentDirectory;
                string newPath = System.IO.Path.Combine(activeDir, "Images");
                System.IO.Directory.CreateDirectory(newPath);

                newPath = System.IO.Path.Combine(newPath, tile.TileType.ToString());
                System.IO.Directory.CreateDirectory(newPath);

                newPath = System.IO.Path.Combine(newPath, tile.Zoom.ToString());
                System.IO.Directory.CreateDirectory(newPath);

                newPath = System.IO.Path.Combine(newPath, tile.X.ToString());
                System.IO.Directory.CreateDirectory(newPath);

                newPath = System.IO.Path.Combine(newPath, tile.Y.ToString());
                System.IO.Directory.CreateDirectory(newPath);

                string newFileName = "tile.png";
                newPath = System.IO.Path.Combine(newPath, newFileName);

                tempBmp.Save(newPath, ImageFormat.Png);
                tempBmp.Dispose();

Your code seems overcomplicated, do you really need read image and then resave it? 您的代码似乎过于复杂,您真的需要读取图像然后重新保存它吗? Why can't you just save downloaded image directly, like this: 为什么不能直接保存下载的图像,像这样:

        public static void GetImageFromUrl(string url)
    {
        string RefererUrl = string.Empty;
        int TimeoutMs = 22 * 1000;
        string requestAccept = "*/*";
        string UserAgent = "Mozilla/5.0 (Windows; U; Windows NT 6.0; en-US; rv:1.9.1.7) Gecko/20091221 Firefox/3.5.7";

      //  Bitmap img = null;
        HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);

        request.UserAgent = UserAgent;
        request.Timeout = TimeoutMs;
        request.ReadWriteTimeout = TimeoutMs * 6;
        request.Accept = requestAccept;

        if (!string.IsNullOrEmpty(RefererUrl))
        {
            request.Referer = RefererUrl;
        }

        try
        {
            WebResponse wResponse = request.GetResponse();
            using (HttpWebResponse response = wResponse as HttpWebResponse)
            {
                Stream responseStream = response.GetResponseStream();
                BinaryReader br = new BinaryReader(responseStream);

                FileStream fs = new FileStream(@"c:\pst\1.jpg", FileMode.Create, FileAccess.Write);

                const int buffsize = 1024;
                byte[] bytes = new byte[buffsize];
                int totalread = 0;

                int numread = buffsize;
                while (numread != 0)
                {
                    // read from source
                    numread = br.Read(bytes, 0, buffsize);
                    totalread += numread;

                    // write to disk
                    fs.Write(bytes, 0, numread);
                }

                br.Close();
                fs.Close();


                response.Close();
            }
        }
        catch (Exception)
        {
        }
    } 

You should of course split it into methods and set proper return values 您当然应该将其拆分为方法并设置适当的返回值

You should not call Dispose() on ms and img objects until you have saved it to the file at the end. 在最后将其保存到文件之前, Dispose()msimg对象上调用Dispose()

They are even declared in their own using sections, so you don't need to call Dispose() on them at all, because it is automatically disposed at the exit of each used block (this is really the main reason of using using in the first place!). 他们甚至在自己的声明using的部分,所以你不需要打电话给我们Dispose()都在他们身上,因为它是自动设置在每个使用区块的出口(这是真的很喜欢使用的原因主要using在第一名!)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM