Image masks

This is a code example of iText PDF, discover more.

1st November 2015
admin-marketing

Switch code for this example

MakeJpgMask.java
  1. /**
  2.  * This code sample was written by Bruno Lowagie in answer to this question:
  3.  * http://stackoverflow.com/questions/29096314/how-to-make-an-image-a-qualified-mask-candidate-in-itext
  4.  */
  5. package sandbox.images;
  6.  
  7. import com.itextpdf.text.Document;
  8. import com.itextpdf.text.DocumentException;
  9. import com.itextpdf.text.Image;
  10. import com.itextpdf.text.PageSize;
  11. import com.itextpdf.text.pdf.PdfWriter;
  12.  
  13. import java.awt.image.BufferedImage;
  14. import java.io.ByteArrayOutputStream;
  15. import java.io.File;
  16. import java.io.FileOutputStream;
  17. import java.io.IOException;
  18.  
  19. import javax.imageio.ImageIO;
  20. import sandbox.WrapToTest;
  21.  
  22. @WrapToTest
  23. public class MakeJpgMask {
  24.     public static final String IMAGE = "resources/images/javaone2013.jpg";
  25.     public static final String MASK = "resources/images/berlin2013.jpg";
  26.     public static final String DEST = "results/images/jpg_mask.pdf";
  27.    
  28.     public static void main(String[] args) throws IOException, DocumentException {
  29.         File file = new File(DEST);
  30.         file.getParentFile().mkdirs();
  31.         new MakeJpgMask().createPdf(DEST);
  32.     }
  33.     public void createPdf(String dest) throws IOException, DocumentException {
  34.         Document document = new Document(PageSize.A4.rotate());
  35.         PdfWriter.getInstance(document, new FileOutputStream(dest));
  36.         document.open();
  37.         Image image = Image.getInstance(IMAGE);
  38.         Image mask = makeBlackAndWhitePng(MASK);
  39.         mask.makeMask();
  40.         image.setImageMask(mask);
  41.         image.scaleAbsolute(PageSize.A4.rotate());
  42.         image.setAbsolutePosition(0, 0);
  43.         document.add(image);
  44.         document.close();
  45.     }
  46.    
  47.     public static Image makeBlackAndWhitePng(String image) throws IOException, DocumentException {
  48.         BufferedImage bi = ImageIO.read(new File(image));
  49.         BufferedImage newBi = new BufferedImage(bi.getWidth(), bi.getHeight(), BufferedImage.TYPE_USHORT_GRAY);
  50.         newBi.getGraphics().drawImage(bi, 0, 0, null);
  51.         ByteArrayOutputStream baos = new ByteArrayOutputStream();
  52.         ImageIO.write(newBi, "png", baos);
  53.         return Image.getInstance(baos.toByteArray());
  54.     }
  55. }
Contact

Still have questions? 

We're happy to answer your questions. Reach out to us and we'll get back to you shortly.

Contact us
Stay updated

Join 11,000+ subscribers and become an iText PDF expert by staying up to date with our new products, updates, tips, technical solutions and happenings.

Subscribe Now