Resizing Images Stored in SQL-Server

In SQL-Server we can store images inside database tables directly using the Image column type. And with .NET 2.0 data binding it can automatically convert these images (stored as byte arrays) into System.Drawing.Image classes for you. For instance, say you have a table called Pictures that has a column called Picture of the data type Image. You can create a new data source to this table to generate a strongly typed DataSet and use drag-and drop data binding to automatically display the image in a PictureBox. (For information on connecting to your database and creating strongly typed DataSets watch this video.)

If you don't see a PictureBox icon in the Data Sources window next to the Picture column in your DataTable, you may need to select the PictureBox to associate the byte array with the control:

 

Now you can drag-and-drop the Picture onto your form to set up the data binding to the PictureBox. The binding will automatically handle converting the byte array stored in the column into an image using the System.Drawing.ImageConverter. You can then set the SizeMode property on the PictureBox depending on how you want the image displayed; resized, stretched or otherwise.

But what if you just want to resize the image and not use a PictureBox? In that case you just need to convert the byte array stored in the Picture column into an System.Drawing.Image. Once you have that then you can use methods on this Image class to perform all sorts of transformations. To resize the image, just call GetThumbnailImage and pass it the new size requirements:

Dim resizeImg, origImg As Image

'Get the current row

Dim row As PictureDemoDataSet.PictureRow

row = CType(CType(Me.PictureBindingSource.Current, DataRowView).Row, _

      PictureDemoDataSet.PictureRow)

'Convert byte array to image

Using ms As New System.IO.MemoryStream(row.Picture)

    origImg = Image.FromStream(ms)

    Dim width As Integer = 25

    Dim height As Integer = 25

    'Resize image

    resizeImg = origImg.GetThumbnailImage(width, height, Nothing, Nothing)

End Using

I've attached a simple application that demonstrates these techniques for you to play with. You'll need Visual Basic 2005 and SQL Server 2005 (or Express) to run.

Enjoy! 

PictureResizing.zip