LibTiff.NET Tiff to WPF Image

本文关键字:WPF Image to Tiff NET LibTiff | 更新日期: 2023-09-27 17:58:31

我正在使用LibTiff.NET读取多页Tiff文件。将我的Tiff转换为System.Drawing.Bitmap没有问题,因为它显示在他们的网站上,但我想要的是BitmapSource或类似于WPF的东西。当然,我可以转换已经存在的converted System.Drawing.Bitmap,但由于数据量很大,我正在寻找一种直接从Tiff object转换的方法。

有什么建议吗?也许使用ReadRGBAImage方法,它会返回一个带颜色的int数组?

第1版:

我尝试了以下操作,但只得到一张由灰色条纹组成的图像:

int[] raster = new int[height * width];
im.ReadRGBAImage(width, height, raster);
byte[] bytes = new byte[raster.Length * sizeof(int)];
Buffer.BlockCopy(raster, 0, bytes, 0, bytes.Length);
int stride = raster.Length / height;
image.Source = BitmapSource.Create(
     width, height, dpiX/*ex 96*/, dpiY/*ex 96*/,
     PixelFormats.Indexed1, BitmapPalettes.BlackAndWhite, bytes, 
     /*32/*bytes/pixel * width*/ stride);

第2版:

也许这有助于转换为System.Drawing.Bitmap

LibTiff.NET Tiff to WPF Image

好的,我已经下载了库。完整的解决方案是:

byte[] bytes = new byte[imageSize * sizeof(int)];
int bytesInRow = width * sizeof(int);
//Invert bottom and top
for (int row = 0; row < height; row++)
    Buffer.BlockCopy(raster, row * bytesInRow, bytes, (height - row -1) * bytesInRow, bytesInRow);

//Invert R and B bytes
byte tmp;
for (int i = 0; i < bytes.Length; i += 4)
{
    tmp = bytes[i];
    bytes[i] = bytes[i + 2];
    bytes[i + 2] = tmp;
}
int stride = width * 4;
Image = BitmapSource.Create(
        width, height, 96, 96,
        PixelFormats.Pbgra32, null, bytes, stride);

解决方案有点复杂。事实上,WPF不支持rgba32格式。因此,为了正确显示图像,应该交换R和B字节。另一个tric是tif图像是倒置加载的。这需要一些额外的操作。

希望这能有所帮助。