简体   繁体   English

为什么需要指定裁剪分辨率?

[英]Why do I need to specify a resolution for cropping?

I wrote a method to crop images in C#. 我编写了一种在C#中裁剪图像的方法。 It does it by creating a new Bitmap and drawing onto it a specified rectangle (the area to be cropped) from the original image. 通过创建新的位图并在其上从原始图像绘制指定的矩形(要裁剪的区域)来完成此操作。

For the images I've tried with it was generating wrong results. 对于我尝试过的图像,它产生了错误的结果。 The size of the resulting image was right, but the content was it. 生成的图像的大小是正确的,但是内容是正确的。 It was like if the image has been scaled up by 2 and then cropped. 就像图像放大了2幅然后被裁剪一样。 Eventually adding this line fixed it: 最终添加此行将其修复:

result.setResolution(72, 72)

But why do I need a resolution? 但是为什么我需要一个解决方案? I'm just working with pixels, never with inches or centimeters. 我只是在处理像素,而不是英寸或厘米。 Also, what would then be the correct resolution? 另外,正确的分辨率又是什么呢?

The full code is this extension method: 完整的代码是此扩展方法:

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;
}

You are using the incorrect overload of DrawImage. 您正在使用不正确的DrawImage重载。 You should be using the one where you specify the Src and Dest rects. 您应该使用其中指定Src和Dest rect的那个。

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

Try that and let me know in comments if it doesn't work. 尝试一下,如果不起作用请在评论中告知我。

i suspect the answer lies in the way the library actually makes the modification. 我怀疑答案就在于库实际进行修改的方式。 it just copy and pastes around some blocks of memory. 它只是复制并粘贴一些内存块。 the resolution specifies the number of bits/bytes used per pixel. 分辨率指定每个像素使用的位数/字节数。 in order to know how many bytes he needs to copy, he needs to know how many bits/bytes per pixel is used. 为了知道他需要复制多少字节,他需要知道每个像素使用多少位/字节。

therefore i think this is a simple multiplication followed by a memcopy. 因此,我认为这是一个简单的乘法,然后是内存复制。

regards 问候

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM