Apng文件判断

背景:在图片压缩中,根据文件头判断png和jpg文件进行了压缩,但是对apng文件,文件头的前14个字节都一样(89504E470D0A1A0A0000000D4948),导致对apng图片进行压缩,图片白了

解决方法:进一步根据acTL和IHDR判断文件是apng还是png,代码如下:

    private boolean isApng(File file) {
        byte[] buffer = new byte[8];
        try (FileInputStream inputStream = new FileInputStream(file)) {
            inputStream.read(buffer, 0, 8);
            while (true) {
                // Read the chunk length
                int length = readInt(inputStream);
                // Read the chunk type
                inputStream.read(buffer, 0, 4);
                String chunkType = new String(buffer, 0, 4, "UTF-8");
                if (chunkType.equals("acTL") && length == 8) {
                    return true;
                } else {
                    // Skip the chunk data and CRC
                    inputStream.skip(length + 4);
                }
                // Check for the end of the file
                if (inputStream.available() == 0) {
                    break;
                }
            }
            return false;
        } catch (IOException e) {
            return false;
        }
    }

    private int readInt(InputStream inputStream) throws IOException {
        byte[] buffer = new byte[4];
        inputStream.read(buffer, 0, 4);
        return ((buffer[0] & 0xFF) << 24) | ((buffer[1] & 0xFF) << 16) | ((buffer[2] & 0xFF) << 8) | (buffer[3] & 0xFF);
    }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值