mask and clip an image in iTextSharp

Masking and clipping an image in iTextSharp

In the previous page, you leant how to create an image and make the image transparent in a PDF document. In this tutorial, I am going to show you how to mask an image and clip the image.

1. Masking an image

To mask the image, first you need to create a GrayScale image object as you did in the previous tutorial. Then you will transform the image object to a masking image by calling the MakeMask method. Finally, apply the masking image to the original image by using the ImageMask property.

pdf mask imagepdf masked image


//create a document object
var doc = new Document();
//get the current directory
string path ="d:";
//get PdfWriter object
PdfWriter writer=PdfWriter.GetInstance(doc, new FileStream(path + "/pdfdoc.pdf", FileMode.Create));
//open the document for writing
PdfContentByte content = writer.DirectContent;
//create gradient in GrayScale color
byte[] gradient = new byte[256];
for (int i = 0; i < 256; i++)
gradient[i] = (byte)i;

//create an image object
Image imgmask = Image.GetInstance(256, 1, 1, 8, gradient);
//make it a masking image
//create an image object from an image file
Image img = Image.GetInstance("d:/baby1.jpg");
//set the mask to the image
img.ImageMask = imgmask;
doc.Add(new Paragraph("Masked image"));

2. Clipping an image

To clip an image, you need to create a PdfTemplate object that is smaller than the original picture, and add the Image object to it. With the combination of the Clip and NewPath methods, you can specify a new path to clip the picture. In the example code below, the Ellipse shape is used as a path to clip the picture.

PdfTemplate temp =content.CreateTemplate(200, 150);
temp.Ellipse(0, 0,200,150);
Image clipped = Image.GetInstance(temp);
clipped.Rotation =180;
doc.Add(new Paragraph("The masked image after being clipped"));

pdf clipped image


This website intents to provide free and high quality tutorials, examples, exercises and solutions, questions and answers of programming and scripting languages:
C, C++, C#, Java, VB.NET, Python, VBA,PHP & Mysql, SQL, JSP, ASP.NET,HTML, CSS, JQuery, JavaScript and other applications such as MS Excel, MS Access, and MS Word. However, we don't guarantee all things of the web are accurate. If you find any error, please report it then we will take actions to correct it as soon as possible.