This code snippet helps us to generate thumbnail image from the image streams stored in database and in file system.
Creating Thumbnail Image when image stored in database
First, we will see how to generate a thumbnail image from the image stored in a BLOB field.
string imageid = "1";
SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["connectionString"].ConnectionString);
connection.Open();
SqlCommand command = new SqlCommand("select Image from Image where ImageID="+imageid, connection);
SqlDataReader dr = command.ExecuteReader();
dr.Read();
Stream str = new MemoryStream((Byte[])dr[0]);
Bitmap loBMP = new Bitmap(str);
Bitmap bmpOut = new Bitmap(100, 100);
Graphics g = Graphics.FromImage(bmpOut);
g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
g.FillRectangle(Brushes.White, 0, 0, 100, 100);
g.DrawImage(loBMP, 0, 0, 100, 100);
MemoryStream ms = new MemoryStream();
bmpOut.Save(ms, System.Drawing.Imaging.ImageFormat.Png);
byte[] bmpBytes = ms.GetBuffer();
bmpOut.Dispose();
ms.Close();
Response.BinaryWrite(bmpBytes);
connection.Close();
Response.End();
Creating Thumbnail Image when image stored in file system
In this section, we will see how to generate image stored in file system.
string str = context.Server.MapPath(".") + imageurl;
Bitmap bmp = new Bitmap(str);
System.Drawing.Image img = bmp.GetThumbnailImage(100, 100, null, IntPtr.Zero);
MemoryStream ms = new MemoryStream();
img.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
byte[] bmpBytes = ms.GetBuffer();
img.Dispose();
ms.Close();
Response.BinaryWrite(bmpBytes);
Response.End();
In the above code, we are reading a BitMap image object by reading the image from the file system. BitMap object has method called GetThumbnailImage which accepts height and width to create thumbnail image from the existing image. The created thumbnail image is then converted to byte array(bmpBytes) using MemoryStream object and it is outputted by doing a binary write.
|