Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to download an image from an URI and create a bitmap object from it?

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);
    }

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

like image 219
Krzysztof Kaczor Avatar asked Aug 27 '12 13:08

Krzysztof Kaczor


2 Answers

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 link for Bitmap

like image 109
Khurram Avatar answered Nov 15 '22 17:11

Khurram


The easiest way is to open a network stream via a WebClient instance and pass it to the constructor of the Bitmap class:

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");
        }
    }
}
like image 26
Krisztián Balla Avatar answered Nov 15 '22 16:11

Krisztián Balla