我写了一个用C#裁剪图像的方法。它通过创建一个新的Bitmap并从原始图像中绘制一个指定的矩形(要裁剪的区域)来实现。

对于我尝试使用它的图像产生了错误的结果。得到的图像的大小是正确的,但内容是它。就好像图像按比例放大了2然后裁剪。最后添加此行修复它:

result.setResolution(72, 72)

但为什么我需要一个解决方案呢?我只是处理像素,从不使用英寸或厘米。那么,什么是正确的分辨率?

完整的代码是这种扩展方法:

public static Bitmap Crop(this Image image, int x, int y, int width, int height) {
    Bitmap result = new Bitmap(width, height);
    result.SetResolution(72, 72);

    // Use a graphics object to draw the resized image into the bitmap.
    using (Graphics graphics = Graphics.FromImage(result)) {
        // High quality.
        graphics.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;
        graphics.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
        graphics.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
        // Draw the image into the target bitmap.
        graphics.DrawImage(image, 0, 0, new Rectangle(x, y, width, height), GraphicsUnit.Pixel);
    }

    return result;
}
有帮助吗?

解决方案

您正在使用DrawImage的错误重载。 您应该使用指定Src和Dest rects的那个。

graphics.DrawImage(image, new Rectangle(0, 0, width, height), new Rectangle(x, y, width, height), GraphicsUnit.Pixel);

尝试一下,如果不起作用,请在评论中告诉我。

其他提示

我怀疑答案在于库实际进行修改的方式。它只是复制和粘贴一些内存块。分辨率指定每个像素使用的位数/字节数。为了知道他需要复制多少字节,他需要知道每个像素使用了多少位/字节。

因此我认为这是一个简单的乘法,然后是记忆。

问候

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top