Click here to Skip to main content
16,016,795 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I need to crop image from center in dimensions ex : 640*960 and 640*1136
How to get image without aspect ratio calculation.
Posted
Comments
BillWoodruff 4-Dec-13 6:54am    
Why do you need the aspect ratio if all you are going to do is crop the image ?

I assume you can measure the image, get its width, and height; given those measurements, you can easily calculate the center of the image.

Please explain further.
shriti 3 4-Dec-13 7:09am    
if i will remove aspect ratio then resulting image i get will be distorted


Using Aspect Ratio->

if (image.Width > image.Height)
{
srcWidth = (int)(Math.Round(image.Height * croppedWidthToHeight));
if (srcWidth < image.Width)
{
srcHeight = image.Height;
left = (image.Width - srcWidth) / 2;
}
else
{
srcHeight = (int)Math.Round(image.Height * ((double)image.Width / srcWidth));
srcWidth = image.Width;
top = (image.Height - srcHeight) / 2;
}
}
else
{
srcHeight = (int)(Math.Round(image.Width * croppedHeightToWidth));
if (srcHeight < image.Height)
{
srcWidth = image.Width;
top = (image.Height - srcHeight) / 2;
}
else
{
srcWidth = (int)Math.Round(image.Width * ((double)image.Height / srcHeight));
srcHeight = image.Height;
left = (image.Width - srcWidth) / 2;
}
}
using (Graphics g = Graphics.FromImage(bitmap))
{
g.SmoothingMode = SmoothingMode.HighQuality;
g.PixelOffsetMode = PixelOffsetMode.HighQuality;
g.CompositingQuality = CompositingQuality.HighQuality;
g.InterpolationMode = InterpolationMode.HighQualityBicubic;
g.DrawImage(image, new Rectangle(0, 0, bitmap.Width, bitmap.Height), new Rectangle(left, top, srcWidth, srcHeight), GraphicsUnit.Pixel);
}
finalImage = bitmap;
}


Without Aspect ratio-
Bitmap bmp = new Bitmap(targetWidth, targetHeight);
Graphics grp = Graphics.FromImage(bmp);
grp.DrawImage(image, new Rectangle(0, 0, bmp.Width, bmp.Height), new Rectangle(0, 0, image.Width, image.Height), GraphicsUnit.Pixel);
// return (Image)bmp;
bmp.Save(filePath);

return false;
shriti 3 4-Dec-13 7:14am    
by mistake my issue was posted in solution
BillWoodruff 4-Dec-13 10:44am    
It appears you are doing more than cropping an image: you are scaling the image so it fits in a given bounding area.

What exactly is the problem you experience now ? What's not working ?

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900