使用{{3}}新创建的缩小PDF文件中JPEG图像大小的最佳做法是什么? (我的目标是在图像质量和文件大小之间进行权衡。)
图像创建如下:
Image image = new Image(ImageDataFactory.create(imagePath))
我想提供一个比例因子,例如0.5
,它将一行中的像素数减半。
假设我使用单个3 MB图像生成PDF。我尝试了image.scale(0.5f, 0.5f)
,但生成的PDF文件仍大约为3 MB。我预计它会变小。
因此我猜想嵌入在PDF文件中的源图像不会被触及。但这就是我需要的:应该减少存储在磁盘上的整个PDF文件中的像素总数。
实现这一目标的最简单/推荐方法是什么?
答案 0 :(得分:3)
首先缩放图像,然后使用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));
有关如何缩放图像的更好提示,请参阅How can I resize an image using Java?
如果在添加到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));
答案 1 :(得分:1)
您可以随意设置编写器对象的压缩级别。
PdfWriter writer = new PdfWriter("MyPdf.pdf");
writer.setCompressionLevel(0);
PdfDocument pdf = new PdfDocument(writer);
Document document = new Document(pdf, PageSize.A4);
如果压缩级别为0,那么以pdf呈现的图像将不会占用任何大小。具有图像且没有图像的Pdf尺寸将是相同的。 无论您想要什么样的高度和宽度,都可以进行缩放。
答案 2 :(得分:0)
此documentations中列出的方法是,您可以访问压缩图像并减少存储在磁盘上的整个PDF文件。希望它有所帮助。
下面是代码示例:
/*
* This example was written by Bruno Lowagie in answer to the following question:
* http://stackoverflow.com/questions/30483622/compressing-images-in-existing-pdfs-makes-the-resulting-pdf-file-bigger-lowagie
*/
package sandbox.images;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.pdf.PRStream;
import com.itextpdf.text.pdf.PdfName;
import com.itextpdf.text.pdf.PdfNumber;
import com.itextpdf.text.pdf.PdfObject;
import com.itextpdf.text.pdf.PdfReader;
import com.itextpdf.text.pdf.PdfStamper;
import com.itextpdf.text.pdf.parser.PdfImageObject;
import java.awt.Graphics2D;
import java.awt.geom.AffineTransform;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import javax.imageio.ImageIO;
import sandbox.WrapToTest;
/**
* @author Bruno Lowagie (iText Software)
*/
@WrapToTest
public class ReduceSize {
public static final String SRC = "resources/pdfs/single_image.pdf";
public static final String DEST = "results/images/single_image_reduced.pdf";
public static final float FACTOR = 0.5f;
public static void main(String[] args) throws DocumentException, IOException {
File file = new File(DEST);
file.getParentFile().mkdirs();
new ReduceSize().manipulatePdf(SRC, DEST);
}
public void manipulatePdf(String src, String dest) throws DocumentException, IOException {
PdfReader reader = new PdfReader(src);
int n = reader.getXrefSize();
PdfObject object;
PRStream stream;
// Look for image and manipulate image stream
for (int i = 0; i < n; i++) {
object = reader.getPdfObject(i);
if (object == null || !object.isStream())
continue;
stream = (PRStream)object;
if (!PdfName.IMAGE.equals(stream.getAsName(PdfName.SUBTYPE)))
continue;
if (!PdfName.DCTDECODE.equals(stream.getAsName(PdfName.FILTER)))
continue;
PdfImageObject image = new PdfImageObject(stream);
BufferedImage bi = image.getBufferedImage();
if (bi == null)
continue;
int width = (int)(bi.getWidth() * FACTOR);
int height = (int)(bi.getHeight() * FACTOR);
if (width <= 0 || height <= 0)
continue;
BufferedImage img = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
AffineTransform at = AffineTransform.getScaleInstance(FACTOR, FACTOR);
Graphics2D g = img.createGraphics();
g.drawRenderedImage(bi, at);
ByteArrayOutputStream imgBytes = new ByteArrayOutputStream();
ImageIO.write(img, "JPG", imgBytes);
stream.clear();
stream.setData(imgBytes.toByteArray(), false, PRStream.NO_COMPRESSION);
stream.put(PdfName.TYPE, PdfName.XOBJECT);
stream.put(PdfName.SUBTYPE, PdfName.IMAGE);
stream.put(PdfName.FILTER, PdfName.DCTDECODE);
stream.put(PdfName.WIDTH, new PdfNumber(width));
stream.put(PdfName.HEIGHT, new PdfNumber(height));
stream.put(PdfName.BITSPERCOMPONENT, new PdfNumber(8));
stream.put(PdfName.COLORSPACE, PdfName.DEVICERGB);
}
reader.removeUnusedObjects();
// Save altered PDF
PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(dest));
stamper.setFullCompression();
stamper.close();
reader.close();
}
}