我正在尝试将 C# 中的图像精确且可预测地缩放到不同的分辨率,包括向上和向下。当我使用 Gimp 等外部工具打开生成的图像时,结果不符合我当前的设置。
public Image Square(Image image, int res) {
Bitmap sq = new Bitmap(res, res, image.PixelFormat);
Graphics canvas = Graphics.FromImage(sq);
canvas.CompositingQuality = CompositingQuality.HighQuality;
canvas.SmoothingMode = SmoothingMode.None;
canvas.InterpolationMode = InterpolationMode.Bicubic;
canvas.DrawImage(sq, 0, 0, res, res);
return sq;
}
缩小时结果还可以(但远非完美),但放大时会产生副作用:
这张图片的分辨率为 2x2 像素。所有像素的 Alpha channel 都设置为不透明。
显然,C# 图形库在缩放图片时引入了透明度。如果给定图像具有透明图片,此方法应该仍然有效,因此移除 alpha channel 不是一个选项。
同样,当缩小图片时,生成的图像的边缘也会出现问题,通常不是很暗就是很透明。
有什么办法可以避免这种行为吗?
编辑:我已经尝试过 NearestNeighbor 仅用于缩小尺度,但结果如下:
编辑 2:使用 WrapMode.TileFlipXY
,透明边缘消失了,但红色只占图像的 25%,而不是应有的 50%:
最佳答案
您要的是 bicubic interpolation你明白了。你想要的是“最近的邻居”选项为 outlined in the docs :
canvas.InterpolationMode = InterpolationMode.NearestNeighbor;
关于c# - 精确缩放图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47292193/