Monday, August 22, 2005

Creating thumbnails from binary content ...

This article would explain the way to create thumbnail images from the binary data in SQL Server. Lets get started.

I) Sample table structure:

Create table [dbo].[ImgTable] (
[ImgId] [int] IDENTITY (1, 1) NOT NULL ,
[Photo] [image] NULL
) ON [Primary] Textimage_on [Primary]
GO

II) Code snippet to create thumbnails

private void Button1_Click(object sender, System.EventArgs e)
{
DataRow oDRow;
int arraySize = new int();

System.Drawing.Image thumb;
System.Drawing.Image originalimg;

SqlConnection oSqlConn = new SqlConnection("Server=dbserver;uid=username;pwd=password;database=northwind");
SqlDataAdapter oSqlDA = new SqlDataAdapter("Select Photo From ImgTable", oSqlConn);

SqlCommandBuilder oSqlCmdBldr = new SqlCommandBuilder(oSqlDA);
DataSet oDS = new DataSet("TblBinaryImages");
byte[] bytImgData = new byte[0];

oSqlDA.Fill(oDS, "TblBinaryImages");
oDRow = oDS.Tables["TblBinaryImages"].Rows[0];
bytImgData = (byte[])oDRow["Photo"];

MemoryStream stream = new MemoryStream((byte[])oDRow["Photo"]);
originalimg = System.Drawing.Image.FromStream(stream);

//Vadivel :: You can pass the width and height as Querystring.
thumb = originalimg.GetThumbnailImage(100, 100, null, new System.IntPtr());

// Sending Response JPEG type to the browser.
Response.ContentType = "image/jpeg";
thumb.Save(Response.OutputStream,System.Drawing.Imaging.ImageFormat.Jpeg);

// Disposing the objects.
originalimg.Dispose();
thumb.Dispose();
}

No comments: