webp 做一種壓縮體積更小的圖片,如今在大部分瀏覽器中已經可以使用。
谷歌提供了sdk以及一些工具方便 我們使用webp格式,具體參考:官網
sejda-pdf/webp-imageio
在Java中,可以使用這個庫:sejda-pdf/webp-imageio: Java ImageIO WebP support
其封裝了多個系統的libwebp庫版本,可以在Linux、Mac、Windows中使用,同時還發布在了Maven中。
但有一個問題,就是這個庫,不能將GIF圖片轉為動態的webp文件。只會將GIF圖片第一幀轉為webp文件,也就是一張靜態的圖片。
簡單使用:
public class ImageUtils {
@Test
public void test() throws IOException {
compress("encoder.jpeg", "jpeg");
compress("encoder.jpg", "jpg");
compress("encoder.png", "png");
// 不會轉換動圖,只會生成一張靜態圖片
compress("encoder.gif", "gif");
}
public void compress(String input, String output) throws IOException {
// Obtain an image to encode from somewhere
File file = new File("src/test/resources/image/" + input);
BufferedImage image = ImageIO.read(file);
// Encode it as webp using default settings
ImageIO.write(image, "webp", new File("target/" + output + ".webp"));
}
}
我暫時沒有找到提供GIF轉webP動畫的Java庫。
阿里OSS圖片處理
阿里oss支持將圖片處理后保存到oss:[文檔]
相比較上一種方式,支持圖片格式更多,GIF圖片也能很好的處理。
雖然,這樣不會產生圖片流量費用,但根據次數,可能產生數據處理費用。參見:[圖片處理費用]
低規格(800×600以下):0.025元/千次
中規格(1600×1200以下):0.1元/千次
所以,可以在將圖片上傳到oss后,進行處理得到新圖片,然后刪除舊的圖片。
StringBuilder processBuildStr = new StringBuilder();
Formatter styleFormatter = new Formatter(processBuildStr);
String styleType = "image/format,webp";
String targetImage = "result.webp";
String sourceImage = "encoder.gif";
styleFormatter.format("%s|sys/saveas,o_%s,b_%s", styleType,
BinaryUtil.toBase64String(targetImage.getBytes()),
BinaryUtil.toBase64String(bucketName.getBytes()));
System.out.println(processBuildStr.toString());
ProcessObjectRequest request = new ProcessObjectRequest(bucketName, sourceImage, processBuildStr.toString());
GenericResult processResult = ossClient.processObject(request);
String json = null;
try {
json = IOUtils.readStreamAsString(processResult.getResponse().getContent(), "UTF-8");
processResult.getResponse().getContent().close();
System.out.println(json);
} catch (IOException e) {
e.printStackTrace();
}
調用 gif2webp
gif2webp 是Google提供的sdk中的一個可執行工具,使用起來也很簡單。
gif2webp.exe .\gif.gif -o gif.webp
webp 壓縮效率
我發現在無損壓縮模式下,GIF格式轉為webp,壓縮效果並不是很好。