我试图通过从中间裁剪将肖像图像裁剪成特定的景观尺寸,而我似乎做错了。现在我有以下代码:
// Check the orientation
if(original.Height > original.Width) {
var bmp = new Bitmap(original);
int cropHeightOffset = (desiredHeight - original.Height) / 2;
var totalArea = new Rectangle(new Point(0, 0),
new Size(original.Width, original.Height));
var cropArea = new Rectangle(new Point(0, cropHeightOffset),
new Size(desiredWidth, desiredHeight));
// Create new blank image of the desired size
var newBmp = new Bitmap(bmp, new Size(desiredWidth, desiredHeight));
// Crop image
var cropper = Graphics.FromImage(newBmp);
// Draw it
cropper.DrawImage(bmp, totalArea, cropArea, GraphicsUnit.Pixel);
// Save
original.Dispose();
newBmp.Save(imagePath, ImageFormat.Jpeg);
}
当发生这种情况时,它基本上会调整图像大小(从而扭曲图像)而不是裁剪图像。
如果我在totalArea
调用中切换cropArea
和cropper.DrawImage
,那么它会从底部裁剪,但它会将图像循环两次(但仍然是正确的大小)。
我对如何正确地做到这一点感到困惑。
<小时/> 编辑:以下是我尝试过的一些例子。有些东西我没有得到,我只是不确定是什么。
使用Oliver的代码:
var targetArea = new Rectangle(new Point(0, 0), new Size(desiredWidth, desiredHeight));
var cropArea = new Rectangle(new Point(0, cropHeightOffset), new Size(desiredWidth, desiredHeight));
...
// Draw it
cropper.DrawImage(bmp, targetArea, cropArea, GraphicsUnit.Pixel);
给了我http://dl.dropbox.com/u/6753359/crop/7278482-2.jpeg
var targetArea = new Rectangle(new Point(0, 0), new Size(desiredWidth, desiredHeight));
var cropArea = new Rectangle(new Point(0, cropHeightOffset), new Size(original.Width, original.Height));
......
// Draw it
cropper.DrawImage(bmp, cropArea, targetArea, GraphicsUnit.Pixel);
给了我http://dl.dropbox.com/u/6753359/crop/7278482-1.jpeg
原始图片为:http://dl.dropbox.com/u/6753359/crop/7278482%20orig.jpeg
答案 0 :(得分:2)
您必须指定目标区域,而不是总面积:
var newSize = new Size(desiredWidth, desiredHeight);
var targetArea = new Rectangle(new Point(0, 0), newSize);
var cropArea = new Rectangle(new Point(0, cropHeightOffset), newSize);
...
cropper.DrawImage(bmp, targetArea, cropArea, GraphicsUnit.Pixel);