压缩现有pdf中的图像会使生成的PDF文件更大(Lowagies调整大小方法和实际压缩方法) [英] Compressing images in existing pdfs makes the resulting PDF file bigger (Lowagies resizing method and real compression method)

查看:180
本文介绍了压缩现有pdf中的图像会使生成的PDF文件更大(Lowagies调整大小方法和实际压缩方法)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

图像压缩有问题.我用这个问题描述的答案 通过Java使用大图像压缩pdf 如果我将FACTOR变量设置为0.9f或1f(原始大小),则生成的pdf文件开始变得大于原始文件.但是,并非所有文件都如此.我自己创建的某些文件正像计划的那样变小,但有些文件却像+ 1/3rd一样变大,并且在它上面的某些图像上出现黑色背景.当我使用正常的图像压缩而不调整图像大小时,情况变得更糟 是我的测试文件.

Im having a problem with image compression. I used the answer described in this question compress pdf with large images via java if i set the FACTOR variable to 0.9f or 1f (original size) the resulting pdf file starts to get bigger than the ORIGINAL. But that is not the case for all files. Some files created by myself are getting smaller like planned but some just get bigger like +1/3rd and i get black backgrounds on some images ontop of it. this is getting even worse when im using the normal image compression without resizing the image This is my test file.

Lowagies方法:(调整图像大小)

Lowagies method: (resize the images)

    // TODO Auto-generated method stub
    PdfName key = new PdfName("ITXT_SpecialId");
    PdfName value = new PdfName("123456789");
    // Read the file
    PdfReader reader = new PdfReader(args[0]);
    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 (value.equals(stream.get(key))) {
        PdfObject pdfsubtype = stream.get(PdfName.SUBTYPE);
        System.out.println(stream.type());
        if (pdfsubtype != null && pdfsubtype.toString().equals(PdfName.IMAGE.toString())) {
            PdfImageObject image = new PdfImageObject(stream);
            BufferedImage bi = image.getBufferedImage();
            if (bi == null) continue;
            int width = (int)(bi.getWidth() * 1f);
            int height = (int)(bi.getHeight() * 1f);
            BufferedImage img = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
            AffineTransform at = AffineTransform.getScaleInstance(1f, 1f);
            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.BEST_COMPRESSION);
            stream.put(PdfName.TYPE, PdfName.XOBJECT);
            stream.put(PdfName.SUBTYPE, PdfName.IMAGE);
            stream.put(key, value);
            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);
        }
    }
    // Save altered PDF
    PdfStamper stamper = new PdfStamper(reader, new FileOutputStream("/Applications/XAMPP/xamppfiles/htdocs/pdf_compress/download/"+args[2]));
    stamper.close();
    reader.close();

我的方法(通过设置图像的质量来使用实际压缩,而不是调整其大小)

My method (Using real compression by setting the quallity of the image instead of resizing it)

        PdfReader reader = new PdfReader(args[0]);

        // Read the file
        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;


            PdfObject pdfsubtype = stream.get(PdfName.SUBTYPE);
            if (pdfsubtype != null && pdfsubtype.toString().equals(PdfName.IMAGE.toString())) {


                System.out.println(pdfsubtype.length());
                PdfImageObject image = new PdfImageObject(stream);

                BufferedImage bi = image.getBufferedImage();


                if (bi == null) continue;
                int width = (int)(bi.getWidth());
                int height = (int)(bi.getHeight());


                if(width <=30 || height <=30){
                    continue;

                }
                BufferedImage img = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
                AffineTransform at = null;
                Graphics2D g = img.createGraphics();
                g.drawRenderedImage(bi, at );
                ByteArrayOutputStream imgBytes = new ByteArrayOutputStream();
                Iterator iter = ImageIO.getImageWritersByFormatName("JPG");
                ImageWriter writer = (ImageWriter)iter.next();
                ImageWriteParam iwp = writer.getDefaultWriteParam();
                iwp.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
// here goes the compression
                iwp.setCompressionQuality(Float.valueOf(args[1]));
                ImageOutputStream imageos = ImageIO.createImageOutputStream(imgBytes);
                writer.setOutput(imageos);
                IIOImage images = new IIOImage(img, null, null);

                writer.write(null,images , iwp);
                imageos.close();
                writer.dispose();

                stream.clear();
                stream.setData(imgBytes.toByteArray(), false, PRStream.BEST_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);
            }
        }           
        PdfStamper stamper = new PdfStamper(reader, new FileOutputStream("/Applications/XAMPP/xamppfiles/htdocs/pdf_compress/download/"+args[2]));
        stamper.setFullCompression();

        stamper.close();
        reader.close();
        System.out.println("Done");

代码有什么问题?我应该使用其他图像压缩方法吗?还有其他吗?

What is wrong with the code? Should i use a different image compression method? Are there any others?

推荐答案

仅替换JPEG时,文件大小已经减小.删除未使用的对象也有帮助:

When I only replace JPEGs, I already get a lower file size. Removing the unused object also helps:

public class ReduceSize {

    public static final String SRC = "resources/pdfs/annual_report_2009.pdf";
    public static final String DEST = "results/images/annual_report_2009.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();
    }
}

这会将10,510 KB文件减少到9,159 KB.当然:字体也占据了相当大的空间.

This reduces the 10,510 KB file to 9,159 KB. Of course: fonts also take up quite some space.

这篇关于压缩现有pdf中的图像会使生成的PDF文件更大(Lowagies调整大小方法和实际压缩方法)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆