首先缩放图像,然后使用iText打开缩放图像.
ImageDataFactory中有一个接受AWT图像的create方法.首先使用AWT工具缩放图像,然后像这样打开它:
String imagePath = "C:\\path\\to\\image.jpg";
java.awt.Image awtImage = ImageIO.read(new File(imagePath));
// scale image here
int scaledWidth = awtImage.getWidth(null) / 2;
int scaledHeight = awtImage.getHeight(null) / 2;
BufferedImage scaledAwtImage = new BufferedImage(scaledWidth, scaledHeight, BufferedImage.TYPE_INT_RGB);
Graphics2D g = scaledAwtImage.createGraphics();
g.drawImage(awtImage, 0, 0, scaledWidth, scaledHeight, null);
g.dispose();
/*
Optionally pick a color to replace with transparency.
Any pixels that match this color will be replaced by tansparency.
*/
Color bgColor = Color.WHITE;
Image itextImage = new Image(ImageDataFactory.create(scaledAwtImage, bgColor));
如果在添加到PDF时仍需要原始大小,请再次将其重新缩放.
itextImage.scale(2f, 2f);
注意:此代码未经测试.
编辑回应对赏金的评论
你让我思考和寻找.似乎iText将AWT图像导入为原始图像.我认为它对待它就像BMP一样,它只是writes the pixel data using /FlateDecode,这可能远远不是最佳的.我能想到实现您的要求的唯一方法是使用ImageIO将缩放后的图像写入文件系统或将ByteArrayOutputStream写为jpeg,然后使用生成的文件/字节打开iText.
这是使用字节数组的更新示例.如果你想更多地了解压缩级别等,refer here.
String imagePath = "C:\\path\\to\\image.jpg";
java.awt.Image awtImage = ImageIO.read(new File(imagePath));
// scale image here
int scaledWidth = awtImage.getWidth(null) / 2;
int scaledHeight = awtImage.getHeight(null) / 2;
BufferedImage scaledAwtImage = new BufferedImage(scaledWidth, scaledHeight, BufferedImage.TYPE_INT_RGB);
Graphics2D g = scaledAwtImage.createGraphics();
g.drawImage(awtImage, 0, 0, scaledWidth, scaledHeight, null);
g.dispose();
ByteArrayOutputStream bout = new ByteArrayOutputStream()
ImageIO.write(scaledAwtImage, "jpeg", bout);
byte[] imageBytes = bout.toByteArray();
Image itextImage = new Image(ImageDataFactory.create(imageBytes));