Click here to Skip to main content
5,790,650 members and growing! (19,396 online)
Email Password   helpLost your password?
Web Development » Charts, Graphs and Images » Images and multimedia     Intermediate

Binary streaming of large images from Database

By TiNgZ aBrAhAm

Explains how to perform drawing on a large image retrieved from the database, and then stream the image with the "Open/Save" option.
VB, Windows, .NET, .NET 1.0, .NET 1.1, GDI+, ASP.NET, VS.NET2002, VS.NET2003, Visual Studio, Dev

Posted: 29 Jun 2004
Updated: 29 Jun 2004
Views: 87,723
Bookmarked: 37 times
Announcements
Loading...



Search    
Advanced Search
Sitemap
12 votes for this Article.
Popularity: 2.60 Rating: 2.41 out of 5
3 votes, 25.0%
1
2 votes, 16.7%
2
2 votes, 16.7%
3
1 vote, 8.3%
4
4 votes, 33.3%
5

Introduction

This explains how to perform drawing operations on a large image retrieved from the database, and then stream the image on the browser, with the "Open/Save" option.

Getting the Image from Database

For this sample code, I have a database table ImageTable which contains a column Image of data type image.

First, we need to fetch the image from the database. Since we need to do some drawing on the image, we convert the image into a System.Drawing.Image. The function below converts the image bytes into the System.Drawing.Image and returns it.

' This function returns the image retrieved from the database

Private Function GetImageFromDB(ByVal ImageID As Integer) As Image    
    Dim image As Image
    ...
    ...

    Try
        sqlCommand = "SELECT Image FROM ImageTable WHERE ImageID = "_
                     + ImageID.ToString()
        
        ...
               
        Dim dr As SqlDataReader
        dr = cmd.ExecuteReader()
        While (dr.Read())

            Dim byt As Byte()
            byt = dr.Item(strImage)
            ' Convert the image bytes to System.Drawing.Image

            Dim bmp As New Bitmap(New System.IO.MemoryStream(byt))
            image = bmp
                    
        End While
    
    ...
    
    End Try

    Return image

End Function

Now, we have to use this image and perform drawing operations on the image, and then stream it as a binary output to the browser. The image is retrieved as:

Dim image As Image
image = GetImageFromDB(ImageID)

Getting a Graphics object

In order to perform drawing operations on the image, we have to use the System.Drawing.Graphics class. You can get the Graphics object directly from the database image if it is not in Indexed Pixel Format. For images with Indexed Pixel Format, we can get the Graphics object by creating a temporary bitmap and then copying the database image onto the bitmap. The code to do this is shown below:

Dim bmpNew As Bitmap
Dim imageNew As Image
Dim objGraphics As Graphics
Try
    objGraphics = Graphics.FromImage(image)               

Catch e As Exception
    ' The image is in indexed pixel format

    ' Create a temp bitmap


    bmpNew = New Bitmap(image.Width, image.Height)
    imageNew = bmpNew

    objGraphics = Graphics.FromImage(imageNew)

    ' Draw the contents of old bitmap to new bitmap

    objGraphics.DrawImage(image, New Rectangle(0, 0, _
                          imageNew.Width, imageNew.Height), _
                          0, 0, image.Width, image.Height, _
                          GraphicsUnit.Pixel)

    image = imageNew

End Try

Drawing on the image

That would retrieve the image from the database and create a Graphics object. Now, perform all the drawing you need to do on the Graphics object. Let's say, write a simple text over the image..

Dim objFont As Font = New Font("Verdana", 12, FontStyle.Bold)
Dim objbrush As Brush = Brushes.Black
Dim rect As New Drawing.RectangleF(10, 10, 200, 50)
Dim objGraphics As Graphics
objGraphics.DrawString("Simple Text", objFont, objbrush, rect)

Binary Streaming

Once we are done with the drawing operations on the image, we stream it to the browser. A simple image.Save(Response.OutputStream, ImageFormat.Jpeg) would have been sufficient for small image files. For large files (say over 1 MB), the image should be streamed in chunks of fixed size.

' Set the content type

Response.ContentType = "image/Jpeg"

Dim ms As MemoryStream = New MemoryStream()
image.Save(ms, Imaging.ImageFormat.Jpeg)
Dim bytImage(ms.Length) As Byte
bytImage = ms.ToArray()
ms.Close()

ms = New MemoryStream(bytImage)
Response.Clear()
Response.AddHeader("Content-Type", "binary/octet-stream")
Response.AddHeader("Content-Length", bytImage.Length.ToString())
Response.AddHeader("Content-Disposition", _
     "attachment; filename=DownloadedImage.jpg; size=" _
     + bytImage.Length.ToString())
Response.Flush()

Dim chunkSize As Integer = 1024

Dim i As Integer
For i = 0 To bytImage.Length Step chunkSize
    ' Everytime check to see if the browser is still connected

    If (Not Response.IsClientConnected) Then
        Exit For
    End If

    Dim size As Integer = chunkSize
    If (i + chunkSize >= bytImage.Length) Then
        size = (bytImage.Length - i)
    End If

    Dim chunk(size - 1) As Byte
    ms.Read(chunk, 0, size)
    Response.BinaryWrite(chunk)
    Response.Flush()
Next
ms.Close()

In this case, I read the bytes and stream them in sizes of 1024. The above code will ultimately throw a "file download" dialog with the "open/save" option, and the user can either open the image from the location or save it to his disk. This is achieved using the lines:

Response.AddHeader("Content-Type", "binary/octet-stream")
Response.AddHeader("Content-Disposition", _
  "attachment; filename=DownloadedImage.jpg; size=" _
  + bytImage.Length.ToString())

Without these lines, the image would be streamed directly to the client and will show up in the browser.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here

About the Author

TiNgZ aBrAhAm



aBrAhAm very strongly believes in "If a man does his best, what else is there?".

He is a software professional, if thats what u call someone who can write code in many languages, including English. His programming experience includes VC++/MFC, Win32, Lotus Notes APIs, ASP.NET, C#, VB.net, .NET 2005, blah blah blah.... [Ctrl + C] and [Ctrl + V] are his most favorite keys.

He was born in God's own country (Kerala, India), brought up in Chennai and now he works at Federal Way, Washington.

Sound engineering is his passion, and he is into composing and recording songs and music. He loves playing 'blak sugar' (thats how he calls his guitar), and fooling around wherever he goes.

In his spare time he keeps wondering why '24 hrs a day is jus not enuf'.

He exists at www.Tingzabraham.com
Location: United States United States

Other popular Charts, Graphs and Images articles:

Article Top
Sign Up to vote for this article
You must Sign In to use this message board.
FAQ FAQ Noise ToleranceSearch Search Messages 
 Layout  Per page   
 Msgs 1 to 5 of 5 (Total in Forum: 5) (Refresh)FirstPrevNext
Generalmemory problems with large imagesmemberNasenbaaer12:57 29 Mar '07  
GeneralDifferent Content-Types of imagesmemberfdelagarza7:31 21 Sep '06  
GeneralImage detailsmemberMsuk6:54 11 Jul '06  
GeneralA little more efficient for streamingmemberNathan Blomquist19:01 30 Jun '04  
GeneralRe: A little more efficient for streamingmemberTiNgZ aBrAhAm19:22 30 Jun '04  

General General    News News    Question Question    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

PermaLink | Privacy | Terms of Use
Last Updated: 29 Jun 2004
Editor: Smitha Vijayan
Copyright 2004 by TiNgZ aBrAhAm
Everything else Copyright © CodeProject, 1999-2009
Web18 | Advertise on the Code Project