我正在尝试构建一个程序,该程序读取tiff文件,选择多个页面。 提取这些页面并将其放入列表
原始tiff具有TiffCompressOption.Ccitt4压缩。
从不同文件中提取x页后,我想使用tifflib重建tiff。 但是,当我创建tiff时,以相同的压缩率看不到页面(可能是损坏的)。当我用另一种压缩方式(RGB上的LZW和Photometrix)重建它时。它行得通,只有tiff的大十倍。
代码在下面。
public bool CreateTiff(List<Bitmap> listBitmap, string fileName)
{
int numberOfPages = listBitmap.Count;
using (Tiff output = Tiff.Open(fileName, "w"))
{
for (int page = 0; page < numberOfPages; ++page)
{
// get bufferData
var bmp = listBitmap[page];
byte[] raster = getImageRasterBytes(bmp, PixelFormat.Format32bppArgb);
output.SetField(TiffTag.IMAGEWIDTH, bmp.Width);
output.SetField(TiffTag.IMAGELENGTH, bmp.Height);
output.SetField(TiffTag.COMPRESSION, Compression.CCITT_T6);
output.SetField(TiffTag.PHOTOMETRIC, Photometric.MINISBLACK);
output.SetField(TiffTag.ROWSPERSTRIP, bmp.Height);
output.SetField(TiffTag.XRESOLUTION, bmp.HorizontalResolution);
output.SetField(TiffTag.YRESOLUTION, bmp.VerticalResolution);
output.SetField(TiffTag.BITSPERSAMPLE, 8);
output.SetField(TiffTag.SAMPLESPERPIXEL, 4);
output.SetField(TiffTag.PLANARCONFIG, PlanarConfig.CONTIG);
output.SetField(TiffTag.EXTRASAMPLES, 1, new short[] { (short)ExtraSample.UNASSALPHA });
output.SetField(TiffTag.PAGENUMBER, page, numberOfPages + 1);
int stride = raster.Length / bmp.Height;
convertSamples(raster, bmp.Width, bmp.Height);
for (int i = 0, offset = 0; i < bmp.Height; i++)
{
output.WriteScanline(raster, offset, i, 0);
offset += stride;
}
output.WriteDirectory();
}
}
Process.Start(fileName);
return true;
}
private static void convertSamples(byte[] data, int width, int height)
{
int stride = data.Length / height;
const int samplesPerPixel = 4;
for (int y = 0; y < height; y++)
{
int offset = stride * y;
int strideEnd = offset + width * samplesPerPixel;
for (int i = offset; i < strideEnd; i += samplesPerPixel)
{
byte temp = data[i + 2];
data[i + 2] = data[i];
data[i] = temp;
}
}
}
private static byte[] getImageRasterBytes(Bitmap bmp, PixelFormat format)
{
Rectangle rect = new Rectangle(0, 0, bmp.Width, bmp.Height);
byte[] bits = null;
try
{
// Lock the managed memory
BitmapData bmpdata = bmp.LockBits(rect, ImageLockMode.ReadWrite, format);
// Declare an array to hold the bytes of the bitmap.
bits = new byte[bmpdata.Stride * bmpdata.Height];
// Copy the values into the array.
System.Runtime.InteropServices.Marshal.Copy(bmpdata.Scan0, bits, 0, bits.Length);
// Release managed memory
bmp.UnlockBits(bmpdata);
}
catch
{
return null;
}
return bits;
}