Java 用户上传如何将图片转为webp格式图片

下载 webp-imageio jar包

GitHub - nintha/webp-imageio-core: Java Image I/O reader and writer for the Google WebP image format without system native libs

这里可以根据官方提示手动编译,也可以下载作者发布好的jar包。github提供了多个版本,我用了前面的几个版本都会报so关联错误,webp-imageio-core-0.1.0.jar应用正常,可以根据自己的要求进行选择。

配置开发环境

在模块的根目录下新建libs文件夹,然后将webp-imageio-core-0.1.0.jar放进去。

配置maven 依赖环境:

<dependency>
            <groupId>com.github.nintha</groupId>
            <artifactId>webp-imageio-core</artifactId>
            <version>0.1.0</version>
            <scope>system</scope>
            <systemPath>${project.basedir}/libs/webp-imageio-core-0.1.0.jar</systemPath>
        </dependency>

配置maven打包选项:

<plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <version>${spring-boot.version}</version>
                <configuration>
                    <includeSystemScope>true</includeSystemScope>
                </configuration>
                <executions>
                    <execution>
                        <goals>
                            <goal>repackage</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>

记住这里需要把,includeSystemScope设置为true,把system环境下的jar包打进去

准备工作做好了就可以开始写代码了

图片处理核心代码

    public static File compressToWebp(MultipartFile sourceImage) throws IOException {
        BufferedImage image = ImageIO.read(sourceImage.getInputStream());
        // Obtain a WebP ImageWriter instance
        ImageWriter writer = ImageIO.getImageWritersByMIMEType("image/webp").next();
        // Configure encoding parameters
        WebPWriteParam writeParam = new WebPWriteParam(writer.getLocale());
        writeParam.setCompressionMode(WebPWriteParam.MODE_DEFAULT);
        File file = new File(sourceImage.getOriginalFilename().substring(0, sourceImage.getOriginalFilename().lastIndexOf(".")) + ".webp");
        FileImageOutputStream fileImageOutputStream = new FileImageOutputStream(file);
        // Configure the output on the ImageWriter
        writer.setOutput(fileImageOutputStream);
        // Encode
        writer.write(null, new IIOImage(image, null, null), writeParam);
        fileImageOutputStream.flush();
        fileImageOutputStream.close();
        return file;
    }

将上传图片文件转为本地的webp文件。

经过测试上传的jpg图片,经过webp转化后可以从500+k倒100+k,但是显示保证了图片清晰度。

imageio感觉很不错,保证无损情况下的图片大小降低。thumbnailator也可以,就是不支持webp,而且将图片进行压缩后,会降低图片清晰度

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

流光影下

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值