Skip to content

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; }
  1. 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!