我试图通过从中间裁剪来将肖像图像裁剪成特定的景观尺寸,而我似乎在做错事。现在,我有以下代码:我的裁剪逻辑有什么问题?
// 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);
}
发生这种情况时它本质上调整图像大小(从而扭曲它),而不是种植它。
如果我在cropper.DrawImage
调用中切换totalArea
和cropArea
,则它会从底部开始裁剪,但它将图像循环两次(但仍是正确的大小)。
我完全困惑于如何正确地做到这一点。
编辑:以下是我尝试过的一些事例。有什么我没有得到,我只是不知道是什么。
使用奥利弗代码:
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
我可能是错的,但是从MSDN文档,我认为'DrawImage'第二个参数应在*目的地*位图的区域,所以它应该有裁剪区域的高度和宽度。 – 2012-01-11 21:38:30
这不是我在上面的代码中告诉它的吗? – KallDrexx 2012-01-11 21:41:18
不;您将原始区域作为第二个参数,将目标区域作为第三个参数。 – 2012-01-11 21:49:12