将TIFF像素纵横比更改为正方形
-
23-08-2019 - |
题
我正在尝试在乘法TIFF文件上执行条形码识别。但是TIFF文件正在从传真服务器(我无法控制的)中传给我,该服务器使用非方面像素纵横比保存TIFF。这导致图像由于纵横比而被严重压制。我需要将TIFF转换为方形像素纵横比,但不知道如何在C#中做到这一点。我还需要拉伸图像,以使更改纵横比仍然使图像清晰可见。
有人在C#中做到了吗?还是有人使用了将执行此类过程的图像库?
解决方案
如果其他人遇到同一问题,这是我最终解决这个烦人问题的超级简单方法。
using System.Drawing;
using System.Drawing.Imaging;
// The memoryStream contains multi-page TIFF with different
// variable pixel aspect ratios.
using (Image img = Image.FromStream(memoryStream)) {
Guid id = img.FrameDimensionsList[0];
FrameDimension dimension = new FrameDimension(id);
int totalFrame = img.GetFrameCount(dimension);
for (int i = 0; i < totalFrame; i++) {
img.SelectActiveFrame(dimension, i);
// Faxed documents will have an non-square pixel aspect ratio.
// If this is the case,adjust the height so that the
// resulting pixels are square.
int width = img.Width;
int height = img.Height;
if (img.VerticalResolution < img.HorizontalResolution) {
height = (int)(height * img.HorizontalResolution / img.VerticalResolution);
}
bitmaps.Add(new Bitmap(img, new Size(width, height)));
}
}
其他提示
哦,我忘了提到。 Bitmap.SetResolution
可能有助于解决纵横比问题。下面的内容只是调整大小。
查看 这一页. 。它讨论了调整大小的两种机制。我怀疑在您的情况下,双线性过滤实际上是一个坏主意,因为您可能希望有些好东西和单色。
以下是Naive Resize算法的副本(由Christian Graus撰写,从上面链接的页面撰写),这应该是您想要的。
public static Bitmap Resize(Bitmap b, int nWidth, int nHeight)
{
Bitmap bTemp = (Bitmap)b.Clone();
b = new Bitmap(nWidth, nHeight, bTemp.PixelFormat);
double nXFactor = (double)bTemp.Width/(double)nWidth;
double nYFactor = (double)bTemp.Height/(double)nHeight;
for (int x = 0; x < b.Width; ++x)
for (int y = 0; y < b.Height; ++y)
b.SetPixel(x, y, bTemp.GetPixel((int)(Math.Floor(x * nXFactor)),
(int)(Math.Floor(y * nYFactor))));
return b;
}
另一种机制是滥用 GetThumbNailImage
功能如 这个. 。该代码保持纵横比,但要删除应该简单的代码。
我已经使用了几个图像库,免费图像(开源)和雪地。 (相当昂贵的)免费图像包含AC#包装器,并且在.NET组件中提供了雪地。两者都很好。
在代码中调整它们的大小不可能是不可能的,但是GDI+有时有2个颜色的TIFF会很尴尬。
不隶属于 StackOverflow