从URL获取图像但未完全加载 [英] Get an Image from a URL but it is not loaded completely

查看:130
本文介绍了从URL获取图像但未完全加载的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试从URL获取图像,但是当我将其保存到文件时,它只是实际图像的一半!我搜索了许多网站和解决方案,如HttpWebRequest.BeginGetResponse,因为我认为这是因为我必须缓冲数据,但它不起作用。我不知道我的代码的哪一部分是错的并且出现了这个问题!:(

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! 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. I don't know which part of my code is wrong and making this problem!:(

这是从URL检索图像的代码:

This is the code which retrieve image from 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:

        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

这篇关于从URL获取图像但未完全加载的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆