2012-01-11 21 views
1

我试图通过从中间裁剪来将肖像图像裁剪成特定的景观尺寸,而我似乎在做错事。现在,我有以下代码:我的裁剪逻辑有什么问题?

// 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调用中切换totalAreacropArea,则它会从底部开始裁剪,但它将图像循环两次(但仍是正确的大小)。

我完全困惑于如何正确地做到这一点。


编辑:以下是我尝试过的一些事例。有什么我没有得到,我只是不知道是什么。

使用奥利弗代码:

  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

我可能是错的,但是从MSDN文档,我认为'DrawImage'第二个参数应在*目的地*位图的区域,所以它应该有裁剪区域的高度和宽度。 – 2012-01-11 21:38:30

+0

这不是我在上面的代码中告诉它的吗? – KallDrexx 2012-01-11 21:41:18

+0

不;您将原始区域作为第二个参数,将目标区域作为第三个参数。 – 2012-01-11 21:49:12

回答

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); 
+0

这只有当我有了0,0偏移的croparea时才起作用。当我添加'cropHeightOffset'时,图像会循环。在这两个领域使用cropHeighOffset也不起作用,这只是导致图像调整大小 – KallDrexx 2012-01-11 21:45:04

+0

我更新了问题与我的代码 – KallDrexx 2012-01-11 21:59:45

+0

Nevermind的例子,这个工程。我减法失败,并且我的偏移量是向后计算的(应该是原始的 - 希望的) – KallDrexx 2012-01-11 22:15:18