Tuesday, December 30, 2008

Resize Image with Aspect ratio

Response.ContentType = "Image/Jpeg";
System.Drawing.Image img = System.Drawing.Image.FromFile(@"images1.jpg");
float percent = 100;
if (img.Width > img.Height)
{
if (img.Width > 100)
{
float width = (float)img.Width / 100;
percent = percent / width;
}
}
else
{
if (img.Height > 100)
{
float heigth = (float)img.Height / 100;
percent = percent / heigth;
}
}

System.Drawing.Image image = ImageManipulator.ScaleByPercent(img,(int)percent);
image.Save(Response.OutputStream, System.Drawing.Imaging.ImageFormat.Jpeg);
img.Dispose();



public class ImageManipulator
{
public ImageManipulator()
{
//
// TODO: Add constructor logic here
//
}
public static Image ScaleByPercent(Image imgPhoto, int Percent)
{
float nPercent = ((float)Percent / 100);

int sourceWidth = imgPhoto.Width;
int sourceHeight = imgPhoto.Height;
int sourceX = 0;
int sourceY = 0;

int destX = 0;
int destY = 0;
int destWidth = (int)(sourceWidth * nPercent);
int destHeight = (int)(sourceHeight * nPercent);

Bitmap bmPhoto = new Bitmap(destWidth, destHeight,
PixelFormat.Format24bppRgb);
bmPhoto.SetResolution(imgPhoto.HorizontalResolution,
imgPhoto.VerticalResolution);

Graphics grPhoto = Graphics.FromImage(bmPhoto);
grPhoto.InterpolationMode = InterpolationMode.HighQualityBicubic;

grPhoto.DrawImage(imgPhoto,
new Rectangle(destX, destY, destWidth, destHeight),
new Rectangle(sourceX, sourceY, sourceWidth, sourceHeight),
GraphicsUnit.Pixel);

grPhoto.Dispose();
return bmPhoto;
}
}

No comments: