Code For Keeps:- WPF/Silverlight Retrieve Images from DB/Url

WPF and Silverlight are all about images and styling and the one thing i end up doing a lot is extracting images from Databases, websites and showing them on a screen…and the code to do this is really hard to remember. So keep this code in your safe!!

1. Get Image from a byte[]: If your image is stored in the DB you will generally get it back as a binary. You can get the byte array by doing a ToArray() on the binay

public BitmapImage ImageFromBuffer(Byte[] bytes)
       {
           MemoryStream stream = new MemoryStream(bytes);
           BitmapImage image = new BitmapImage();
           image.SetSource(stream);
           stream.Close();
           return image;
       }

2. Get Image from a Url

public BitmapImage GetImageFromUrl(string imageUrl )

{

          const int BYTESTOREAD = 100000;

        WebRequest myRequest = WebRequest.Create(new Uri(imageUrl, UriKind.Absolute));
        myRequest.Timeout = -1;
        WebResponse myResponse = myRequest.GetResponse();
        Stream ReceiveStream = myResponse.GetResponseStream();
        BinaryReader br = new BinaryReader(ReceiveStream);
        MemoryStream memstream = new MemoryStream();
        byte[] bytebuffer = new byte[BYTESTOREAD];
        int BytesRead = br.Read(bytebuffer, 0, BYTESTOREAD);

        while (BytesRead > 0)
        {
            memstream.Write(bytebuffer, 0, BytesRead);
            BytesRead = br.Read(bytebuffer, 0, BYTESTOREAD);
        }
        BitmapImage image = new BitmapImage();
        image.BeginInit();
        memstream.Seek(0, SeekOrigin.Begin);

        image.StreamSource = memstream;
        image.EndInit();

        return image

     }

Hope if helps make your UI prettier!!!

Cennest!

Advertisements

About Cennest
Cennest is the brainchild of a group of IT Professionals keen to try their hand in the world of IT Freelancing. After working in the corpora

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: