问题
I'm trying to write a routine that will save a WPF BitmapSource as a JPEG encoded TIFF using LibTiff.net. Using the examples provided with LibTiff I came up with the following:
private void SaveJpegTiff(BitmapSource source, string filename)
{
if (source.Format != PixelFormats.Rgb24) source = new FormatConvertedBitmap(source, PixelFormats.Rgb24, null, 0);
using (Tiff tiff = Tiff.Open(filename, "w"))
{
tiff.SetField(TiffTag.IMAGEWIDTH, source.PixelWidth);
tiff.SetField(TiffTag.IMAGELENGTH, source.PixelHeight);
tiff.SetField(TiffTag.COMPRESSION, Compression.JPEG);
tiff.SetField(TiffTag.PHOTOMETRIC, Photometric.RGB);
tiff.SetField(TiffTag.ROWSPERSTRIP, source.PixelHeight);
tiff.SetField(TiffTag.XRESOLUTION, source.DpiX);
tiff.SetField(TiffTag.YRESOLUTION, source.DpiY);
tiff.SetField(TiffTag.BITSPERSAMPLE, 8);
tiff.SetField(TiffTag.SAMPLESPERPIXEL, 3);
tiff.SetField(TiffTag.PLANARCONFIG, PlanarConfig.CONTIG);
int stride = source.PixelWidth * ((source.Format.BitsPerPixel + 7) / 8);
byte[] pixels = new byte[source.PixelHeight * stride];
source.CopyPixels(pixels, stride, 0);
for (int i = 0, offset = 0; i < source.PixelHeight; i++)
{
tiff.WriteScanline(pixels, offset, i, 0);
offset += stride;
}
}
MessageBox.Show("Finished");
}
This converts the image and I can see a JPEG image but the colours are messed up. I'm guessing I'm missing a tag or two for the TIFF or something is wrong like the Photometric interpretation but am not entirely clear on what is needed.
Cheers,
回答1:
It's not clear what do you mean by saying " colours are messed up" but probably you should convert BGR samples of BitmapSource
to RGB ones expected by LibTiff.Net.
I mean, make sure the order of color channels is RGB (most probably, it's not) before feeding pixels to WriteScanline
method.
来源:https://stackoverflow.com/questions/12557127/saving-bitmapsource-as-tiff-encoded-jpeg-using-libtiff-net