get width and height of webp with java

﹥>﹥吖頭↗ 提交于 2020-12-12 11:41:10

问题


When I Upload a WEBP file to Controller, I want to get the width and height with java. It returns null when I use the following code:

Image image = ImageIO.read(uploadFile);

When I search on the Internet I find webp-imageio.jar could be used but it's too complex. Is there any easy way to achieve that?


回答1:


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.

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).

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



来源:https://stackoverflow.com/questions/53228624/get-width-and-height-of-webp-with-java

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!