如何从URI下载图像并从中创建位图对象?

Krz*_*zor 9 c# windows-phone

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

    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);
    }
Run Code Online (Sandbox Code Playgroud)

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

Khu*_*ram 24

这是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);
Run Code Online (Sandbox Code Playgroud)

位图的MSDN链接


Jen*_*lly 7

最简单的方法是通过打开一个网络流WebClient的实例,并把它传递给构造函数中的位图类:

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");
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 有趣的图像选择 (2认同)