14

我正在尝试从网站下载图像并基于该图像创建位图。它看起来像这样:

    public void test()
    {
            PostWebClient client = new PostWebClient(callback);
            cookieContainer = new CookieContainer();
            client.cookies = cookieContainer;
            client.download(new Uri("SITE"));
    }

    public void callback(bool error, string res)
    {
            byte[] byteArray = UnicodeEncoding.UTF8.GetBytes(res);

            MemoryStream stream = new MemoryStream( byteArray );
            var tmp = new BitmapImage();
            tmp.SetSource(stream);
    }

我在回调方法的最后一行收到“未指定错误”。有趣的事实是,如果我使用 BitmapImage(new Uri("SITE")) 它工作得很好......(我不能这样做,因为我想从那个 URL 获取 cookie。图像是 jpg。PostWebClient 类-> http://paste.org/53413

4

4 回答 4

34

这是 Bitmap 类文档中最简单的代码。

  System.Net.WebRequest request = 
        System.Net.WebRequest.Create(
        "http://www.microsoft.com//h/en-us/r/ms_masthead_ltr.gif");
    System.Net.WebResponse response = request.GetResponse();
    System.IO.Stream responseStream = 
        response.GetResponseStream();
    Bitmap bitmap2 = new Bitmap(responseStream);

位图的 MSDN 链接

于 2013-12-24T08:25:41.583 回答
10

最简单的方法是通过WebClient实例打开网络流并将其传递给Bitmap构造函数:

using (WebClient wc = new WebClient())
{
    using (Stream s = wc.OpenRead("http://hell.com/leaders/cthulhu.jpg"))
    {
        using (Bitmap bmp = new Bitmap(s))
        {
            bmp.Save("C:\\temp\\octopus.jpg");
        }
    }
}
于 2015-09-17T07:30:09.690 回答
3

你可以试试下面的代码:

        private Bitmap LoadPicture(string url)
        {
            HttpWebRequest wreq;
            HttpWebResponse wresp;
            Stream mystream;
            Bitmap bmp;

            bmp = null;
            mystream = null;
            wresp = null;
            try
            {
                wreq = (HttpWebRequest)WebRequest.Create(url);
                wreq.AllowWriteStreamBuffering = true;

                wresp = (HttpWebResponse)wreq.GetResponse();

                if ((mystream = wresp.GetResponseStream()) != null)
                    bmp = new Bitmap(mystream);
            }
            finally
            {
                if (mystream != null)
                    mystream.Close();

                if (wresp != null)
                    wresp.Close();
            }
            return (bmp);
        }
于 2013-01-18T10:03:53.533 回答
0

试试这个:

            string url ="http://www.google.ru/images/srpr/logo11w.png"
            PictureBox picbox = new PictureBox();
            picbox.Load(url);
            Bitmap bitmapRemote = (Bitmap) picbox.Image;

url - 互联网图像,我们创建新的实例对象 PictureBox,然后调用NOT ASYNC过程从 url 加载图像,当图像检索到图像作为位图。您也可以使用线程处理表单,在其他线程中调用 load 并在完成时通过 deleate 方法检索图像。

于 2015-07-09T07:45:06.720 回答