我正在尝试对多页 tiff 文件执行条形码识别。但是 tiff 文件来自传真服务器(我无法控制),它以非方形像素纵横比保存 tiff。由于纵横比,这导致图像被严重挤压。我需要将 tiff 转换为方形像素纵横比,但不知道如何在 C# 中执行此操作。我还需要拉伸图像,以便更改纵横比仍然使图像清晰可见。
有人用 C# 做过这个吗?或者有没有人使用过一个图像库来执行这样的过程?
我正在尝试对多页 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
可能有助于解决纵横比问题。下面的东西只是关于调整大小。
看看这个页面。它讨论了两种调整大小的机制。我怀疑在你的情况下双线性过滤实际上是一个坏主意,因为你可能想要漂亮的单色的东西。
下面是天真的调整大小算法的副本(由 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
滥用该功能。该代码保持纵横比,但删除执行该操作的代码应该很简单。
我已经使用几个图像库 FreeImage(开源)和 Snowbound 完成了这项工作。(相当昂贵)FreeImage 具有 ac# 包装器,并且 Snowbound 在 .Net 程序集中可用。两者都运作良好。
在代码中调整它们的大小应该不是不可能的,但是 2 色 tiff 有时对于 GDI+ 来说很尴尬。
免责声明:我在 Atalasoft 工作
我们的.NET 成像 SDK可以做到这一点。我们写了一篇知识库文章来展示如何使用我们的产品,但您可以适应其他 SDK。基本上你需要重新采样图像并调整 DPI。