我正在尝试理解并实现一段用于Tiff压缩的代码。
我已经使用了2种不同的技术 - 使用第三方dll的LibTiff.NEt(第一种方法很笨重)和图像保存方法http://msdn.microsoft.com/en-us/library/ytz20d80%28v=vs.110%29.aspx(第二种方法仅适用于Windows 7机器,但不适用于Windows 2003或2008服务器)。
现在我正在寻找第三种方法。
using System.Windows.Forms;
using System.Windows.Media.Imaging;
using System.Drawing.Imaging;
int width = 800;
int height = 1000;
int stride = width/8;
byte[] pixels = new byte[height*stride];
// Try creating a new image with a custom palette.
List<System.Windows.Media.Color> colors = new List<System.Windows.Media.Color>();
colors.Add(System.Windows.Media.Colors.Red);
colors.Add(System.Windows.Media.Colors.Blue);
colors.Add(System.Windows.Media.Colors.Green);
BitmapPalette myPalette = new BitmapPalette(colors);
// Creates a new empty image with the pre-defined palette
BitmapSource image = BitmapSource.Create(
width,
height,
96,
96,
System.Windows.Media.PixelFormats.BlackWhite,
myPalette,
pixels,
stride);
FileStream stream = new FileStream(Original_File, FileMode.Create);
TiffBitmapEncoder encoder = new TiffBitmapEncoder();
encoder.Compression = TiffCompressOption.Ccitt4;
encoder.Frames.Add(BitmapFrame.Create(image));
encoder.Save(stream);
但我对这里发生的事情并不完全了解。
显然有某种内存流正在应用压缩技术。但我有点困惑如何将此应用于我的具体案例。我有一个原始的tiff文件,我想使用此方法将其压缩设置为CCITT并将其保存回来。有人可以帮忙吗?
我复制了上面的代码并运行了代码。但我的结束输出文件是一个纯黑色背景图像。虽然从积极的方面来说它是正确的压缩类型。
http://msdn.microsoft.com/en-us/library/ms616002%28v=vs.110%29.aspx
答案 0 :(得分:0)
LibTiff.net有点笨重,因为它基于LibTiff,它有一系列问题。
我的公司(Atalasoft)能够相当轻松地完成这项任务,而free version of the SDK将通过一些限制完成您想要的任务。重新编码文件的代码如下所示:
public bool ReencodeFile(string path)
{
AtalaImage image = new AtalaImage(path);
if (image.PixelFormat == PixelFormat.Pixel1bppIndexed)
{
TiffEncoder encoder = new TiffEncoder();
encoder.Compression = TiffCompression.Group4FaxEncoding;
image.Save(path, encoder, null); // destroys the original - use carefully
return true;
}
return false;
}
你应该注意的事情:
我希望代码至少检查一下。如果您倾向于提供更好地保留文件内容的解决方案,那么您可能希望这样做:
public bool ReencodeFile(string origPath, string outputPath)
{
if (origPath == outputPath) throw new ArgumentException("outputPath needs to be different from input path.");
TiffDocument doc = new TiffDocuemnt(origPath);
bool needsReencoding = false;
for (int i=0; i < doc.Pages; i++) {
if (doc.Pages[i].PixelFormat == PixelFormat.Pixel1bppIndexed) {
doc.Pages[i] = new TiffPage(new AtalaImage(origPath, i, null), TiffCompression.Group4FaxEncoding);
needsReencoding = true;
}
}
if (needsReendcoding)
doc.Save(outputPath);
return needsReencoding;
}
此解决方案将尊重文档中的所有页面以及文档元数据。