posted on Sunday, February 29, 2004 9:37 AM
by
warstar
Cropping image
So i was bizzy yesterday night till about 3:00 am with a problem of how the h*ll do i crop a image and after a lot of trying i gave up but found a nice function in some code example by i don't know who but it didn't work great i got a “A generic error occurred in GDI+. “ when i called the function and tryed to save the image.
The counter against this i found out very fast is:
System.Drawing.Image imageRigth = Crop(image,200,200,AnchorPosition.Center);
using(Bitmap bitmap = new Bitmap(imageRigth))
{
bitmap.Save(MapPath(fileName), imageRigth.RawFormat);
}
So now i can finaly crop the pictures i upload :)
The function i found:
enum AnchorPosition
{
Top,
Center,
Bottom,
Left,
Right
}
static System.Drawing.Image Crop(System.Drawing.Image imgPhoto, int Width, int Height, AnchorPosition Anchor)
{
int sourceWidth = imgPhoto.Width;
int sourceHeight = imgPhoto.Height;
int sourceX = 0;
int sourceY = 0;
int destX = 0;
int destY = 0;
float nPercent = 0;
float nPercentW = 0;
float nPercentH = 0;
nPercentW = ((float)Width/(float)sourceWidth);
nPercentH = ((float)Height/(float)sourceHeight);
if(nPercentH < nPercentW)
{
nPercent = nPercentW;
switch(Anchor)
{
case AnchorPosition.Top:
destY = 0;
break;
case AnchorPosition.Bottom:
destY = (int)(Height - (sourceHeight * nPercent));
break;
default:
destY = (int)((Height - (sourceHeight * nPercent))/2);
break;
}
}
else
{
nPercent = nPercentH;
switch(Anchor)
{
case AnchorPosition.Left:
destX = 0;
break;
case AnchorPosition.Right:
destX = (int)(Width - (sourceWidth * nPercent));
break;
default:
destX = (int)((Width - (sourceWidth * nPercent))/2);
break;
}
}
int destWidth = (int)(sourceWidth * nPercent);
int destHeight = (int)(sourceHeight * nPercent);
Bitmap bmPhoto = new Bitmap(Width, Height, System.Drawing.Imaging.PixelFormat.Format24bppRgb);
bmPhoto.SetResolution(imgPhoto.HorizontalResolution, imgPhoto.VerticalResolution);
Graphics grPhoto = Graphics.FromImage(bmPhoto);
grPhoto.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
grPhoto.DrawImage(imgPhoto,
new Rectangle(destX,destY,destWidth,destHeight),
new Rectangle(sourceX,sourceY,sourceWidth,sourceHeight),
GraphicsUnit.Pixel);
grPhoto.Dispose();
return bmPhoto;
}