2011-03-31 58 views
2

我从这里(SO)拍摄了一个代码来裁剪图像。我在包含白色字体上的黑色文本的位图上试过。我得到的结果是一个完全没有内容的白色输出。裁剪一个位图给出一个空位图

 // create new bitmap with desired size and same pixel format 
     Bitmap croppedBitmap = new Bitmap(rect.Width, rect.Height, bitmap.PixelFormat); 

     // create Graphics "wrapper" to draw into our new bitmap 
     // "using" guarantees a call to gfx.Dispose() 
     using (Graphics gfx = Graphics.FromImage(croppedBitmap)) 
     { 
      // draw the wanted part of the original bitmap into the new bitmap 
      gfx.DrawImage(bitmap, 0, 0, rect, GraphicsUnit.Pixel); 
     } 

     return croppedBitmap; 

任何猜测?

PS如果我当然油漆裁剪它的工作

编辑

如果我裁剪我的照片,例如工程....

附录

代码:

矩形

 Rectangle 1: 8 50, 95, 80, 30 // invoice number 
     Rectangle 2: 625, 778, 475, 22 // Total amount 

CropImage():

public static Bitmap CropImage(Bitmap bitmap, Rectangle rect) 
    { 
     Bitmap croppedBitmap = new Bitmap(rect.Width, rect.Height, bitmap.PixelFormat); 

     using (Graphics gfx = Graphics.FromImage(croppedBitmap)) 
     { 
      gfx.DrawImage(bitmap, 0, 0, rect, GraphicsUnit.Pixel); 
     } 

     return croppedBitmap; 
    } 

图片: (敏感数据被隐藏,我只剩下我试图裁剪部分) http://img33.imageshack.us/img33/5703/modelx.png

+0

您是否调试过程序并检查代码中的所有变量是否保存了正确的数据?这可能看起来像一个错误的路径问题或类似的问题恕我直言 – BigFatBaby 2011-03-31 10:38:53

+0

是的,我做了我的变量是好的 – CoolStraw 2011-03-31 10:39:11

+0

问题从你已经采取代码的链接。 – 2011-03-31 10:41:23

回答

1

固定代码:

Rectangle rect = new Rectangle(625, 778, 475, 22); 

    Bitmap bitmap = Bitmap.FromFile(@"C:\m.png") as Bitmap; 

    Bitmap croppedBitmap = new Bitmap(bitmap, rect.Width, rect.Height); 
    croppedBitmap.SetResolution(bitmap.HorizontalResolution, bitmap.VerticalResolution); 

    using (Graphics gfx = Graphics.FromImage(croppedBitmap)) 
    { 
     gfx.DrawImage(bitmap, 0, 0, rect, GraphicsUnit.Pixel); 
    } 

    croppedBitmap.Save(@"C:\m-1.png", System.Drawing.Imaging.ImageFormat.Png); 
+0

Habjan现在我明白它看起来像分辨率不一样,我测量了Paint中的目标零件,它仍然给出了上面看到的矩形的错误点...例如,对于发票号码,我可以看到整个数字,也可以看到底部边框和一些文字,这意味着矩形正在变大。但另一方面,整个框架似乎占用了一片空白区域,甚至没有太多奇怪的数量区域..任何猜测? – CoolStraw 2011-03-31 12:49:52

+0

我做了2个修改,位图croppedBitmap = new Bitmap(bitmap,rect.Width,rect.Height);和croppedBitmap.SetResolution(bitmap.Horizo​​ntalResolution,bitmap.VerticalResolution); – HABJAN 2011-03-31 12:52:43

+0

这是我得到的结果:http://img219.imageshack.us/i/63972302.png – HABJAN 2011-03-31 12:56:14