Code for re size image in asp.net, It also maintain the aspect ratio and image quality.
private void GenerateThumbnail(byte[]
byteArray, int thumbnailSize)
{
// Convert byte array into stream
Stream fStream = new
MemoryStream(byteArray);
Bitmap photo = new
Bitmap(fStream);
// maintain aspect ratio
int width, height;
if (photo.Width > photo.Height)
{
width = thumbnailSize;
height = photo.Height * thumbnailSize / photo.Width;
}
else
{
width = photo.Width * thumbnailSize / photo.Height;
height = thumbnailSize;
}
Size resizeImageSize = new
Size(width, height);
System.Drawing.Image img =
System.Drawing.Image.FromStream(fStream);
System.Drawing.Image thumbnailImage =
img.GetThumbnailImage(resizeImageSize.Width, resizeImageSize.Height, null, IntPtr.Zero);
// use high quality conversion
using (Graphics
graphic = Graphics.FromImage(thumbnailImage))
{
graphic.CompositingQuality = CompositingQuality.HighQuality;
graphic.SmoothingMode = SmoothingMode.HighQuality;
graphic.InterpolationMode = InterpolationMode.HighQualityBicubic;
Rectangle rect = new
Rectangle(0, 0, resizeImageSize.Width,
resizeImageSize.Height);
graphic.DrawImage(thumbnailImage, rect);
using (MemoryStream
imageStream = new MemoryStream())
{
thumbnailImage.Save(imageStream, System.Drawing.Imaging.ImageFormat.Jpeg);
// convert back into byte array
byte[] imageContent = new Byte[imageStream.Length];
imageStream.Position = 0;
imageStream.Read(imageContent, 0, (int)imageStream.Length);
context.Response.ContentType = "image/jpeg";
context.Response.OutputStream.Write(imageContent, 0, imageContent.Length);
}
}
}