将tiff像素长宽比改为平方

我正在尝试在多页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可能有助于解决宽高比问题。 以下内容只是resize。

看看这个页面 。 它讨论了两种resize的机制。 我怀疑在你的情况下双线性过滤实际上是一个坏主意,因为你可能想要好看和单色。

下面是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函数。 该代码保持宽高比,但删除执行该操作的代码应该很简单。

我用几个图像库,FreeImage(开源)和Snowbound完成了这个。 (相当昂贵)FreeImage有一个ac#wrapper,Snowbound可以在.Net程序集中使用。 两者都运作良好。

在代码中调整它们的大小不应该是不可能的,但是GDI +有时会使用2种颜色tiff。

免责声明:我在Atalasoft工作

我们的.NET Imaging SDK可以做到这一点。 我们编写了一篇知识库文章来展示如何使用我们的产品,但您可以适应其他SDK。 基本上您需要重新采样图像并调整DPI。