How to import TIF into DICOM in DicomObjects
In DicomObjects CLR 4.8 version, TIF is natively supported by System.Drawing. In DicomObjects Core 5/8 verison, as we use SkiaSharp imaging library which does not support TIF, a bit of a user code is required.
The following sample code demonstrates how to import TIF into DicomImage object in both versions of DicomObjects.
DicomObjects.NET 4.8
DicomImage class
DicomImage image = new DicomImage();
image.Import(tif_file_path);
DicomDataSet class
DicomDataSet ds = new DicomDataSet();
ds.Import(tif_file_path);
DicomObjects.Core 5/8
DicomImage class with BitMiracle.LibTiff library
public static DicomImageCollection ImportTiffR(Stream tiffStream)
{
DicomImageCollection results = new DicomImageCollection();
// open a Tiff stored in the memory stream, and grab its pixels
using Tiff tifImg = Tiff.ClientOpen("", "r", tiffStream, new TiffStream());
if (tifImg == null)
throw new DataException("Could not open incoming image");
int pageCount = 0;
do
{
// Read the width and height of the current page
int width = tifImg.GetField(TiffTag.IMAGEWIDTH)[0].ToInt();
int height = tifImg.GetField(TiffTag.IMAGELENGTH)[0].ToInt();
// Read raster data
int[] raster = new int[width * height];
if (!tifImg.ReadRGBAImageOriented(width, height, raster, Orientation.TOPLEFT))
throw new InvalidDataException($"Invalid TIF image {pageCount}"); // Not a valid TIF image
// store the pixels
var pixels = new SKColor[width * height];
for (int y = 0; y < height; y++)
for (int x = 0; x < width; x++)
{
int arrayOffset = y * width + x;
int rgba = raster[arrayOffset];
pixels[arrayOffset] = new SKColor((byte)Tiff.GetR(rgba), (byte)Tiff.GetG(rgba),
(byte)Tiff.GetB(rgba), (byte)Tiff.GetA(rgba));
}
using SKBitmap bitmap = new SKBitmap(width, height);
bitmap.Pixels = pixels;
results.Add(new DicomImage(bitmap));
}
while (tifImg.ReadDirectory()); // Move to the next page
return results;
}