We use cookies to give you the best experience on our website. If you continue to browse, then you agree to our privacy policy and cookie policy. Image for the cookie policy date
Unfortunately, activation email could not send to your email. Please try again.
Syncfusion Feedback

How to convert color image to black and white/gray image in PDF

Platform: WinForms |
Control: PDF
Tags: pdf, grayscale

We can change color image to black and white/gray image in an existing PDF with the help of ExtractImages and ReplaceImage features and find the code snippet and sample below.

Code snippet for Converting Color image to black and white\gray image:

public Bitmap ConvertToBlackandWhite(Bitmap image)
{
 Bitmap bitmap = new Bitmap(image);
 for (int i = 0; i < bitmap.Width; i++)
 {
   for (int j = 0; j < bitmap.Height; j++)
   {
     int ser = (bitmap.GetPixel(i, j).R + bitmap.GetPixel(i, j).G + bitmap.GetPixel(i, j).B) / 3;
     bitmap.SetPixel(i, j, Color.FromArgb(ser, ser, ser));
   }
 }
return bitmap;
}

 

Code snippet to Replace image in PDF:

private void button1_Click(object sender, EventArgs e)
{ 
 //Loading the existing document.
 PdfLoadedDocument ldoc = new PdfLoadedDocument("input.pdf");
 
 PdfLoadedPageCollection loadedPages = ldoc.Pages;
 
 //iterate through the page.
 foreach (PdfLoadedPage lpage in loadedPages)
 {
  //Extracting images form Page.
  Image[] images = lpage.ExtractImages();
  for (int i = 0; i < lpage.ImagesInfo.Length; i++)
   {
    Bitmap map = new Bitmap(images[i]);
   //Converting color image to black white/gray image.
   PdfImage image = PdfImage.FromImage(ConvertToBlackandWhite(map));
   //Replace the image in the page.
   lpage.ReplaceImage(i, image);
  }
 }
 
 //saving the document
 ldoc.Save("output.pdf");
 ldoc.Close(true);
}

 

Sample:

https://www.syncfusion.com/downloads/support/directtrac/general/ze/Replace_Image-1538519391

 

2X faster development

The ultimate WinForms UI toolkit to boost your development speed.
ADD COMMENT
You must log in to leave a comment

Please sign in to access our KB

This page will automatically be redirected to the sign-in page in 10 seconds.

Up arrow icon

Warning Icon You are using an outdated version of Internet Explorer that may not display all features of this and other websites. Upgrade to Internet Explorer 8 or newer for a better experience.Close Icon

Live Chat Icon For mobile