簡體   English   中英

用java獲取webp的寬度和高度

[英]get width and height of webp with java

當我將 WEBP 文件上傳到 Controller 時,我想用 java 獲取寬度和高度。 當我使用以下代碼時,它返回 null:

Image image = ImageIO.read(uploadFile);

我在網上搜索發現webp-imageio.jar可以使用,但它太復雜了。 有什么簡單的方法可以實現嗎?

是的, Webp Container Sepcs定義了當前使用的Webp 擴展文件格式圖像在與類型、文件大小、是否有任何 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;
    }
}

另請參閱:在 Kotlin 中解析 webp 文件頭以獲取其高度和寬度,但得到意想不到的結果

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM