Friday, August 29, 2008

Send any saved Image over HTTP

How to send an image from your DB in a web page with ASP.NET is well documented. You make an aspx page that sends the bytes on page_load via the response object. If you don't know what type of image you are sending, use the below to figure it out and get your response headers right.
Dim stream As System.IO.MemoryStream Dim img As System.Drawing.Bitmap stream = New System.IO.MemoryStream(ImageBytes) img = System.Drawing.Bitmap.FromStream(stream) If ImageBytes.Length > 0 Then Response.ContentType = "image/" & ImageFormat(img.RawFormat) Response.BinaryWrite(ImageBytes) End If Private Function ImageFormat(ByVal format As System.Drawing.Imaging.ImageFormat) As String If format.Equals(System.Drawing.Imaging.ImageFormat.Bmp) Then Return "BMP" End If If format.Equals(System.Drawing.Imaging.ImageFormat.Emf) Then Return "EMF" End If If format.Equals(System.Drawing.Imaging.ImageFormat.Exif) Then Return "EXIF" End If If format.Equals(System.Drawing.Imaging.ImageFormat.Gif) Then Return "GIF" End If If format.Equals(System.Drawing.Imaging.ImageFormat.Icon) Then Return "Icon" End If If format.Equals(System.Drawing.Imaging.ImageFormat.Jpeg) Then Return "JPEG" End If If format.Equals(System.Drawing.Imaging.ImageFormat.MemoryBmp) Then Return "MemoryBMP" End If If format.Equals(System.Drawing.Imaging.ImageFormat.Png) Then Return "PNG" End If If format.Equals(System.Drawing.Imaging.ImageFormat.Tiff) Then Return "TIFF" End If If format.Equals(System.Drawing.Imaging.ImageFormat.Wmf) Then Return "WMF" End If Return "Unknown" End Function
If you want to actually send the Bitmap you derived from the Bytes, that's a whole other kettle of fish. When you stream the Bitmap you'll have to make sure you set the filter settings on it to high. Setting filter settings on all the various image types is quite a juggle. For gifs you'll even need to define octree quantizing at the very least.

No comments: