2011-12-08 12 views
2

我想裁剪位圖使用此功能,但該位圖可以更小,則作物的種植面積,所以我想在這種情況下,位圖大。裁剪位圖和擴大規模,如果必要

如實例我有一個位圖,其是200x250,如果我使用CropBitmap方法用250x250的我得到一個內存不足的錯誤。它應該返回一個250x250的位圖,其中缺少的左側50像素用白色填充。

我該如何做到這一點?

public Bitmap CropBitmap(Bitmap bitmap, int cropX, int cropY, int cropWidth, int cropHeight) 
{ 
    var rect = new Rectangle(cropX, cropY, cropWidth, cropHeight); 

    if(bitmap.Width < cropWidth || bitmap.Height < cropHeight) 
    { 
     // what now? 
    } 

    return bitmap.Clone(rect, bitmap.PixelFormat); 
} 
+0

這可能有助於調整大小需求:http://snippets.dzone.com/posts/show/4336 – ThePower

回答

3

使用適當的大小創建一個新的位圖。然後得到一個System.Drawing.Graphics,並使用它來創建的空白區域,並插入源圖像。事情是這樣的:

if (bitmap.Width < cropWidth && bitmap.Height < cropHeight) 
    { 
     Bitmap newImage = new Bitmap(cropWidth, cropHeight, bitmap.PixelFormat); 
     using (Graphics g = Graphics.FromImage(newImage)) 
     { 
      // fill target image with white color 
      g.FillRectangle(Brushes.White, 0, 0, cropWidth, cropHeight); 

      // place source image inside the target image 
      var dstX = cropWidth - bitmap.Width; 
      var dstY = cropHeight - bitmap.Height; 
      g.DrawImage(bitmap, dstX, dstY); 
     } 
     return newImage; 
    } 

注意,我在外if表達代替了||&&。要使其與||一起使用,您必須計算源區域並使用another overload of Graphics.DrawImage

+0

我必須將'dstX = cropWidth - bitmap.Width'到'dstX = bitmap.Width - cropWidth'但工作 - 謝謝! (和dstY一樣) – Marc