Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cropping images in Itext

Tags:

java

crop

itext

is there an easy way to crop an Image in Itext?

I have the following code:

URL url = new URL(imgUrl);

connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
iStream = connection.getInputStream();
img = new Jpeg(url);

// a method like 
// img.crop(x1, y1, x2, y2) would be nice.

Now I want to "delete" a strip of let's say 20 pixels left and 20 pixels right. Is there an easy way to do this?

like image 393
Luixv Avatar asked Dec 06 '22 18:12

Luixv


2 Answers

Here is another way to crop an image using PdfTemplate.

public static Image cropImage(Image image, PdfWriter writer, float x, float y, float width, float height) throws DocumentException {
    PdfContentByte cb = writer.getDirectContent();
    PdfTemplate t = cb.createTemplate(width, height);
    float origWidth = image.getScaledWidth();
    float origHeight = image.getScaledHeight();
    t.addImage(image, origWidth, 0, 0, origHeight, -x, -y);
    return Image.getInstance(t);
}

Notice this doesn't require calling t.rectangle(), t.clip() or t.newPath().

like image 79
Nathan Villaescusa Avatar answered Dec 21 '22 05:12

Nathan Villaescusa


Nathan's solution almost worked for me. The only problem left was white margins because of PdfTemplate having the same size as image to crop.

My solution:

public Image cropImage(PdfWriter writer, Image image, float leftReduction, float rightReduction, float topReduction, float bottomReduction) throws DocumentException {
    float width = image.getScaledWidth();
    float height = image.getScaledHeight();
    PdfTemplate template = writer.getDirectContent().createTemplate(
            width - leftReduction - rightReduction,
            height - topReduction - bottomReduction);
    template.addImage(image,
            width, 0, 0,
            height, -leftReduction, -bottomReduction);
    return Image.getInstance(template);
}
like image 32
sdf3qrxewqrxeqwxfew3123 Avatar answered Dec 21 '22 05:12

sdf3qrxewqrxeqwxfew3123