2

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,

making
  • 408
  • 6
  • 21

1 Answers1

0

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.

Bobrovsky
  • 13,789
  • 19
  • 80
  • 130
  • 2
    The colour being messed up is a little difficult to describe but using one of my test images which was mainly white, grey and red. The white becomes magenta, the grey green and the red bright green. Changing RGB to BGR made no difference. Oddly enough, if I save it as LZW then the tiff and the colours are fine. This problem occurs when I change the compression to JPEG. Edit: This set me thinking about something I read in the JPEG TIFF Application note. The photometric interpretation is wrong - for JPEG it should be YCBCR. I changed this and it's all now working. Thanks, – making Sep 24 '12 at 20:25