2009-07-30 65 views
0

我写了一种在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; 
} 

回答

1

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

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

试试看,如果它不起作用,让我知道在评论中。

-1

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

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

关于

+0

图像的格式不应该定义每像素多少个字节?它是RGB? RGBA?他们是长期的还是漂浮的?然后只是复制我告诉它的像素。 – Pablo 2009-07-30 08:49:36

+0

好,是的。但格式只有如何存储数据的信息。根据格式的不同,分辨率可能是可变的,因此格式不能准确知道。我猜花车不适用。 它是什么类型的格式?或者是未知的? 如果省略行 result.SetResolution(72,72); 关于 – Atmocreations 2009-07-30 10:08:20

+0

我认为视频卡使用RGBA与浮动。如果我省略了分辨率,并且让我们说,我裁剪了(0,0,100,100),我得到了一张100乘100的图像,其中一张大约60乘60的原始图像伸出。 – Pablo 2009-07-30 13:19:07