Change colors of black-and-white TIFF after converting from PDF

Convert PDF, Images, Colors
10/24/2011

Downloads

In this article, we will demonstrate how to change the color palette after converting a PDF document to 1bpp TIFF in C#.

Sample Image.png
In the following code sample, we render a PDF to a 1bpp TIFF. Then create a bitmap from the TIFF, create a new color palette, edit the entries of this palette and assign this new palette to the bitmap.

1 static void Main(string[] args) 2 { 3 Document document = new Document(new FileStream(@"..\..\input.pdf", FileMode.Open)); 4 5 // Convert the PDF Document to TIFF file 6 ConvertToTiffOptions tiffOptions = new ConvertToTiffOptions(300.0, TiffCompression.CcittG3); 7 8 string tempPath = @"..\..\tmp.tiff"; 9 using (FileStream drawImage = new FileStream(tempPath, 10 FileMode.OpenOrCreate, FileAccess.Write)) 11 { 12 document.Pages[0].ConvertToTiff(drawImage, tiffOptions); 13 } 14 15 string tiffPath = @"..\..\newImage.bmp"; 16 using (Bitmap tiff = new Bitmap(tempPath)) 17 { 18 // Create a new colorpalette 19 System.Drawing.Imaging.ColorPalette palette = Create1bbPalette(); 20 21 // Set the palette to other colors 22 palette.Entries[0] = System.Drawing.Color.FromArgb(0, 0, 64, 128); 23 palette.Entries[1] = System.Drawing.Color.FromArgb(0, 223, 233, 245); 24 25 // Set the palette of the bitmap to the new palette 26 // Palette entries must be changed before assign the palette to the bitmap 27 tiff.Palette = palette; 28 29 // Save the new image with the new colorpalette 30 tiff.Save(tiffPath, System.Drawing.Imaging.ImageFormat.Bmp); 31 } 32 33 File.Delete(tempPath); 34 } 35 36 static protected System.Drawing.Imaging.ColorPalette Create1bbPalette() 37 { 38 Bitmap bitmap = 39 new Bitmap(1, 1, System.Drawing.Imaging.PixelFormat.Format1bppIndexed); 40 System.Drawing.Imaging.ColorPalette palette = bitmap.Palette; 41 bitmap.Dispose(); 42 return palette; 43 }