【发布时间】:2016-06-07 11:02:59
【问题描述】:
我需要在经典java中提取webp图片的宽高
我搜索了库,找到了 webp-imageio,但它无法提取图像大小
对于 jpg/png/gif 等其他格式,我使用的 ImageIO 仅从标题中提取大小(但遗憾的是它无法处理 webp)
如何使用 webp 做同样的事情?
问候
【问题讨论】:
我需要在经典java中提取webp图片的宽高
我搜索了库,找到了 webp-imageio,但它无法提取图像大小
对于 jpg/png/gif 等其他格式,我使用的 ImageIO 仅从标题中提取大小(但遗憾的是它无法处理 webp)
如何使用 webp 做同样的事情?
问候
【问题讨论】:
这个项目webp-imageio-core 可以帮助你。 它集成了 webp 转换器本机系统库(dll/so/dylib)。
下载并导入您的项目。示例代码:
public static void main(String args[]) throws IOException {
String inputWebpPath = "test_pic/test.webp";
String outputJpgPath = "test_pic/test_.jpg";
String outputJpegPath = "test_pic/test_.jpeg";
String outputPngPath = "test_pic/test_.png";
// Obtain a WebP ImageReader instance
ImageReader reader = ImageIO.getImageReadersByMIMEType("image/webp").next();
// Configure decoding parameters
WebPReadParam readParam = new WebPReadParam();
readParam.setBypassFiltering(true);
// Configure the input on the ImageReader
reader.setInput(new FileImageInputStream(new File(inputWebpPath)));
// Decode the image
BufferedImage image = reader.read(0, readParam);
ImageIO.write(image, "png", new File(outputPngPath));
ImageIO.write(image, "jpg", new File(outputJpgPath));
ImageIO.write(image, "jpeg", new File(outputJpegPath));
}
然后您可以使用 ImageIO 从标题中提取大小。
【讨论】:
来自我的answer here:
Webp Container Sepcs 定义了当前使用的Webp Extended File Format 图像的开头几位对应于类型、文件大小、是否有任何 alpha、是否有任何动画、高度和宽度等。
虽然文档似乎已经过时(它显示高度和宽度的值对应于索引 20 到 25,但我发现它位于 24 到 29 索引上)。
public class JavaRes {
public static java.awt.Dimension extract(InputStream is) throws IOException {
byte[] data = is.readNBytes(30);
if (new String(Arrays.copyOfRange(data, 0, 4)).equals("RIFF") && data[15] == 'X') {
int width = 1 + get24bit(data, 24);
int height = 1 + get24bit(data, 27);
if ((long) width * height <= 4294967296L) return new Dimension(width, height);
}
return null;
}
private static int get24bit(byte[] data, int index) {
return data[index] & 0xFF | (data[index + 1] & 0xFF) << 8 | (data[index + 2] & 0xFF) << 16;
}
}
另请参阅:Parsing webp file header in Kotlin to get its height and width, but getting unexpected results
【讨论】:
Apache Tika 使用这个metadata extractor library 来读取 webp 的元数据,所以也许它也适合您的需求。
【讨论】: