[英]Why do I need to specify a resolution for cropping?
我编写了一种在C#中裁剪图像的方法。 通过创建新的位图并在其上从原始图像绘制指定的矩形(要裁剪的区域)来完成此操作。
对于我尝试过的图像,它产生了错误的结果。 生成的图像的大小是正确的,但是内容是正确的。 就像图像放大了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 rect的那个。
graphics.DrawImage(image, new Rectangle(0, 0, width, height), new Rectangle(x, y, width, height), GraphicsUnit.Pixel);
尝试一下,如果不起作用请在评论中告知我。
我怀疑答案就在于库实际进行修改的方式。 它只是复制并粘贴一些内存块。 分辨率指定每个像素使用的位数/字节数。 为了知道他需要复制多少字节,他需要知道每个像素使用多少位/字节。
因此,我认为这是一个简单的乘法,然后是内存复制。
问候
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.