【问题标题】:get width and height of webp with java用java获取webp的宽度和高度
【发布时间】:2018-11-09 15:27:02
【问题描述】:

当我将 WEBP 文件上传到控制器时,我想用 java 获取宽度和高度。当我使用以下代码时它返回 null:

Image image = ImageIO.read(uploadFile);

当我在互联网上搜索时,我发现webp-imageio.jar 可以使用,但它太复杂了。有什么简单的方法可以实现吗?

【问题讨论】:

    标签: java webp


    【解决方案1】:

    是的,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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-12-26
      • 1970-01-01
      • 2012-10-10
      • 2021-06-30
      • 1970-01-01
      • 1970-01-01
      • 2010-11-18
      • 2023-04-09
      相关资源
      最近更新 更多