2011-03-31 35 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