【问题标题】:Cropping a bitmap gives an empty bitmap裁剪位图会得到一个空位图
【发布时间】:2011-07-26 19:00:04
【问题描述】:

我从这里 (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

【问题讨论】:

  • 您是否调试过程序并检查代码中的所有变量是否包含正确的数据?这似乎是一个错误的路径问题或类似恕我直言
  • 是的,我的变量很好
  • 发布您从哪里获取代码的问题链接。
  • 矩形的值是多少??
  • @Javed:我已经阅读了全部内容,除了代码之外没有任何相关内容。 @Aliostad:不要担心 rect 它设置为正确的值。

标签: c# image graphics image-processing crop


【解决方案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);

【讨论】:

  • Habjan 现在我知道它的分辨率看起来不一样,我在 Paint 中测量了目标部分,但它仍然为您在上面看到的矩形给出错误的点......例如,对于发票编号我可以看到整个数字,还可以看到底部边框和一些文字,这意味着矩形占据了更大的框架。但另一方面,总框架似乎占据了一个空白区域,甚至不是数量区域,这也很奇怪......有什么猜测吗?
  • 我做了2个改动,BitmapcroppedBitmap = new Bitmap(bitmap, rect.Width, rect.Height);和croppedBitmap.SetResolution(bitmap.Horizo​​ntalResolution, bitmap.VerticalResolution);
  • maaaan...我没有看到第二个变化!你震撼了我的世界伙伴!它就像一个魅力!我真的不知道该怎么说谢谢,但谢谢!
猜你喜欢
  • 2019-05-10
  • 2013-03-25
  • 2015-12-11
  • 1970-01-01
  • 2015-05-05
  • 1970-01-01
  • 2012-11-08
  • 2011-10-18
  • 2012-12-02
相关资源
最近更新 更多