下载 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 instanceImageWriter writer = ImageIO.getImageWritersByMIMEType("image/webp").next();// Configure encoding parametersWebPWriteParam 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 ImageWriterwriter.setOutput(fileImageOutputStream);// Encodewriter.write(null, new IIOImage(image, null, null), writeParam);fileImageOutputStream.flush();fileImageOutputStream.close();return file;}
将上传图片文件转为本地的webp文件。
经过测试上传的jpg图片,经过webp转化后可以从500+k倒100+k,但是显示保证了图片清晰度。
imageio感觉很不错,保证无损情况下的图片大小降低。thumbnailator也可以,就是不支持webp,而且将图片进行压缩后,会降低图片清晰度