如何从 URI 下载图像并从中创建位图对象? [英] How to download an image from an URI and create a bitmap object from it?

查看:34
本文介绍了如何从 URI 下载图像并从中创建位图对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm trying to download image from a website and create bitmap based on that image. It looks like this:

    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

I receive "Unspecified error" on last line of callback method. Interesting fact is that if I use BitmapImage(new Uri("SITE")) it works well... (I can't do this like that because I want to grab cookies from that URL. The image is an jpg. PostWebClient class -> http://paste.org/53413

推荐答案

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

This is the simplest code from Bitmap class documentation.

  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 链接

这篇关于如何从 URI 下载图像并从中创建位图对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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