Cropping a bitmap gives an empty bitmap
I've taken a code from here (SO) that crops images. I tried it o开发者_运维知识库n bitmaps containing black text on white font. The result i get in return is a completely white output with no content.
// 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;
Any guess?
PS if i crop in paint of course it does work
edit
If I crop a picture of me for example it works....
Appendix
Code:
Rectangles:
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;
}
Image: (Sensitive data is hidden, I only left the part I'm trying to crop) http://img33.imageshack.us/img33/5703/modelx.png
Fixed code:
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);
精彩评论