java压缩pdf体积,图片体积

pdf整体进行压缩,图片进行压缩

java 复制代码
        // 生成主证书的PDF路径  创建一个文件
        String pdfPath = UploadDown.createFile(".pdf");
          outputStream = new FileOutputStream(pdfPath);
             bufferedOutputStream = new BufferedOutputStream(outputStream);
            writer = PdfWriter.getInstance(document, bufferedOutputStream);
            writer.setCompressionLevel(compressionLevel); // 压缩9
            writer.setFullCompression(); // 全面压缩

发现压缩力度不大,主要还是要对pdf中的图片进行压缩,我这里压缩图片的精度设置成2,具体根据你的业务逻辑来,

java 复制代码
 public static Image optimizeImage(String source) {
        // 这个自己调,如果图片过大,可以调小这个数字
        double quality = 0.2;
        try {
            ByteArrayOutputStream os = new ByteArrayOutputStream();
            System.out.println("压缩图片路径:"+source);
            if (source.startsWith("http://") || source.startsWith("https://") || source.startsWith("ftp://")) {
                Thumbnails.of(new URL(source))
                        .scale(1)
                        .outputQuality(quality)
                        .toOutputStream(os);
            } else {
                Thumbnails.of(source)
                        .scale(1)
                        .outputQuality(quality)
                        .toOutputStream(os);
            }
            byte[] bytes = os.toByteArray();
            // 压缩后的图片用流接收
            Image image = Image.getInstance(bytes);
            return image;
        } catch (Exception e) {
            log.error("压缩图片失败", e);
            e.printStackTrace();
            throw new MyException("压缩图片失败"+e.getMessage());
        }
    }

压缩图片报错的话:

报错信息:javax.imageio.IIOException: Unsupported Image Type

是图片的格式对不上

添加下面的依赖试试:

XML 复制代码
     <!-- cmyk格式图片转换 -->
        <dependency>
            <groupId>com.twelvemonkeys.imageio</groupId>
            <artifactId>imageio-jpeg</artifactId>
            <version>3.3</version>
        </dependency>
        <dependency>
            <groupId>com.twelvemonkeys.imageio</groupId>
            <artifactId>imageio-tiff</artifactId>
            <version>3.3</version>
        </dependency>
相关推荐
yudiandian20141 分钟前
03 Eclipse 配置 JDK 环境
java·ide·eclipse
_码力全开_2 分钟前
P1005 [NOIP 2007 提高组] 矩阵取数游戏
java·c语言·c++·python·算法·矩阵·go
陈一Tender5 分钟前
JavaWeb后端实战(登录认证 & 令牌技术 & 拦截器 & 过滤器)
java·开发语言·spring boot·mysql
Camel卡蒙5 分钟前
红黑树详细介绍(五大规则、保持平衡操作、Java实现)
java·开发语言·算法
jerryinwuhan9 分钟前
机器人模拟器(python)
开发语言·python·机器人
孤廖32 分钟前
吃透 C++ 栈和队列:stack/queue/priority_queue 用法 + 模拟 + STL 标准实现对比
java·开发语言·数据结构·c++·人工智能·深度学习·算法
我命由我1234535 分钟前
Android 对话框 - 对话框全屏显示(设置 Window 属性、使用自定义样式、继承 DialogFragment 实现、继承 Dialog 实现)
android·java·java-ee·android studio·android jetpack·android-studio·android runtime
驰羽40 分钟前
[GO]GORM中的Tag映射规则
开发语言·golang
Full Stack Developme44 分钟前
java.net 包详解
java·python·.net
非凡的世界1 小时前
深入理解 PHP 框架里的设计模式
开发语言·设计模式·php