简体   繁体   English

用java获取webp的宽度和高度

[英]get width and height of webp with java

When I Upload a WEBP file to Controller, I want to get the width and height with java.当我将 WEBP 文件上传到 Controller 时,我想用 java 获取宽度和高度。 It returns null when I use the following code:当我使用以下代码时,它返回 null:

Image image = ImageIO.read(uploadFile);

When I search on the Internet I find webp-imageio.jar could be used but it's too complex.我在网上搜索发现webp-imageio.jar可以使用,但它太复杂了。 Is there any easy way to achieve that?有什么简单的方法可以实现吗?

Yes, the Webp Container Sepcs defines that the Webp Extended File Format images which are currently in use has headers in the starting few bits corresponding to the type, file size, is there any alpha, is there any animation, height and width etc.是的, Webp Container Sepcs定义了当前使用的Webp 扩展文件格式图像在与类型、文件大小、是否有任何 alpha、是否有任何动画、高度和宽度等对应的起始几位中具有标题。

Though the docs seems to be outdated (it shows that the value of height and width corresponds to index 20 to 25 but rather I found it to be on 24 to 29 indexes).尽管文档似乎已经过时(它显示高度和宽度的值对应于索引 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;
    }
}

See also: Parsing webp file header in Kotlin to get its height and width, but getting unexpected results另请参阅:在 Kotlin 中解析 webp 文件头以获取其高度和宽度,但得到意想不到的结果

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM