Reputation: 232
I'm using LibTiff.NET
to read a multipage Tiff file. It's no problem to convert my Tiff into a System.Drawing.Bitmap
, since it's shown on their website, but what I want is a BitmapSource
or something comparable to use in WPF
.
Of course, I can convert the already converted System.Drawing.Bitmap
, but since the amount of data is quite big, I am looking for a method to convert directly from the Tiff object
.
Any suggestions? Maybe with the ReadRGBAImage method, that returns an int array with the colors?
Edit1:
I tried the following but only get an image consisting of gray stripes:
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);
Edit2:
Maybe this helps, it is for conversion to System.Drawing.Bitmap
.
Upvotes: 2
Views: 1234
Reputation: 2062
Ok I've downloaded the lib. The full solution is:
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);
The solution is a bit more complex. In fact WPF don't support rgba32 format. So to display the image correctly R and B bytes should be swapped. Another tric is that tif image is loaded upside down. This needs some additional manipulation.
Hope this helps.
Upvotes: 1