【问题标题】:Why do I need to specify a resolution for cropping?为什么我需要指定裁剪分辨率?
【发布时间】:2009-07-30 06:44:39
【问题描述】:

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

【问题讨论】:

    标签: c# .net image resolution crop


    【解决方案1】:

    您使用了不正确的 DrawImage 重载。 您应该使用指定 Src 和 Dest rects 的那个。

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

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

    【讨论】:

      【解决方案2】:

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

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

      问候

      【讨论】:

      • 图像的格式不应该定义每个像素多少字节吗?是RGB吗? RGBA?它们是整数、长整数还是浮点数?然后复制我告诉它的像素。
      • 是的,确实如此。但格式仅包含如何存储数据的信息。根据格式的不同,分辨率可能是可变的,因此格式无法精确知道。我猜花车不适用。它是什么类型的格式?还是未知?如果省略行 result.SetResolution(72, 72); 会发生什么问候
      • 我认为显卡使用带有浮点数的 RGBA。如果我省略分辨率,假设我裁剪(0, 0, 100, 100),我会得到一个 100 x 100 的图像,其中一张大约 60 x 60 的原始图片被拉伸。
      猜你喜欢
      • 2012-08-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-02-21
      • 2013-01-18
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多