Java中的ImageIo支持webp解析
Java 的 ImageIO 默认不支持 WebP 格式。要读取 WebP 格式的图片,我们需要添加额外的依赖和配置
<dependency><groupId>org.sejda.webp-imageio</groupId><artifactId>webp-imageio-sejda</artifactId><version>0.1.0</version>
</dependency>
我们下面做一个 webp信息获取
@Data@Builderpublic static class ImageInfo{private Integer width;private Integer height;/*** 字节*/private Long size;/*** type 例如 "png"*/private String type;/*** 处理的视频*/private File file;private byte[] imageByte;public static ImageInfo withWidthHeight(Integer width, Integer height){return ImageInfo.builder().width(width).height(height).build();}public static ImageInfo withSize(Long size){return ImageInfo.builder().size(size).build();}public static ImageInfo withType(String type){return ImageInfo.builder().type(type).build();}public static ImageInfo withWidthHeightTypeSize(Integer width, Integer height,String type,Long size){return ImageInfo.builder().width(width).height(height).size(size).type(type).build();}public static ImageInfo withAll(Integer width,Integer height,String type,Long size,byte[] content){return ImageInfo.builder().width(width).height(height).type(type).imageByte(content).size(size).build();}public ImageInfo file(File file){this.file = file;return this;}public ImageInfo imageByte(byte[] imageByte){this.imageByte = imageByte;return this;}}
public static ImageInfo getImageDetail(String strUrl) {int retryCount = 0;int maxRetries = 2;while (retryCount < maxRetries) {try {URL url = new URL(strUrl);HttpURLConnection conn = (HttpURLConnection) url.openConnection();conn.setRequestMethod("GET");conn.setConnectTimeout(10 * 1000);try (InputStream inStream = conn.getInputStream()) {// 获取图片字节数组byte[] imageBytes = StreamUtils.copyToByteArray(inStream);// 获取图片尺寸信息BufferedImage sourceImg = ImageIO.read(new ByteArrayInputStream(imageBytes));if (sourceImg == null) {throw new IOException("Failed to read image");}// 获取图片格式String format = getImageFormat(imageBytes);return ImageInfo.withAll(sourceImg.getWidth(),sourceImg.getHeight(),format,(long)imageBytes.length,imageBytes);}} catch (Exception e) {retryCount++;if (retryCount >= maxRetries) {throw new RuntimeException("Failed to get image detail after " + maxRetries + " retries", e);}log.warn("Failed to get image from url: {}, retrying... (attempt {}/{})",strUrl, retryCount, maxRetries);}}throw new RuntimeException("Failed to get image detail");}