有一种简单的方法可以在Itext中裁剪图像吗?
我有以下代码:
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.
现在我想“删除”一条让我们说左边20像素和右边20像素的条带。 有一个简单的方法吗?
答案 0 :(得分:5)
这是使用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);
}
请注意,这不需要调用t.rectangle(),t.clip()或t.newPath()。
答案 1 :(得分:3)
您可以使用剪切路径进行调查。您需要知道JPEG的宽度和高度。代码可能如下所示:
PdfTemplate t = writer.getDirectContent().createTemplate(850, 600);
t.rectangle(x+20,y+20, width-40, height-40);
t.clip();
t.newPath();
t.addImage(img, width, 0, 0, height, x, y);
答案 2 :(得分:3)
我的解决方案:
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);
}
答案 3 :(得分:1)
// 4x6英寸照片高度= 432宽度= 288
// scale
if (isMatchFrame) {
/* width */
proportion = image.getWidth() / width;
image.scaleAbsolute((float) width, image.getHeight() / proportion);
} else {
/* hight */
proportion = image.getHeight() / height;
image.scaleAbsolute(image.getWidth() / proportion, (float) height);
}
// crop
document.setMargins((height - image.getHeight()/proportion) / 2, 0, (width - image.getWidth()/proportion) / 2 , 0);
可以裁剪中心照片。享受它。
答案 4 :(得分:1)
我也遇到过这个问题, 这就是我所做的:
概念: 将图像作为缓冲图像 制作BufferedImage并渲染为Image(iText)
Document document = new Document(PageSize.A4.rotate());
document.open();
//Get the image as Buffere Image
BufferedImage awtImage = ImageIO.read(new URL("image url"));
//Crop: Sample, get Upper Half of the image
BufferedImage awtImageUpper = awtImage.getSubimage(0, 0, awtImage.getWidth(), awtImage.getHeight()/2);
//Make BufferedImage and render as Image (in iText)
ByteArrayOutputStream baosImage = new ByteArrayOutputStream();
ImageIO.write(awtImageUpper, "png", baosImage);
Image iTextImage = Image.getInstance(baosImage.toByteArray());
//Display Image in pdf
document.add(new Paragraph("image Upper half"));
document.add((Element) iTextImage);