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?
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().
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);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With