JAVA判断图片真实格式的方法

判断图片真实格式的方法,文件格式不是看后缀名,而是看文件头的定义

复制代码
 public class ImgUtil {
    public static String imgType(InputStream inputStream) throws IOException {
        // 读取文件前几位
        byte[] fileHeader = new byte[4];
        int read = inputStream.read(fileHeader, 0, fileHeader.length);
        inputStream.close();
        
        // 转为十六进制字符串
        String header = ByteUtil.bytes2Hex(fileHeader);
        
        if (header.contains("FFD8FF")) {
            return "jpg";
        } else if (header.contains("89504E47")) {
            return "png";
        } else if (header.contains("47494638")) {
            return "gif";
        } else if (header.contains("424D")) {
            return "bmp";
        } else if (header.contains("52494646")) {
            return "webp";
        } else if (header.contains("49492A00")) {
            return "tif";
        } else {
            return "unknown";
        }
 
    }
 
    public static String bytes2Hex(byte[] bytes) {
        StringBuilder sb = new StringBuilder();
        for (byte b : bytes) {
            String hex = Integer.toHexString(b & 0xff);
            sb.append(hex.length() == 2 ? hex : ("0"+hex));
        }
        return sb.toString();
    }
 
    public static void main(String[] args) throws IOException {
        String path ="D:\\panda.webp";
        File file = new File(path);
        System.out.println(ImgUtil.imgType(new FileInputStream(file)));
    }
}
复制代码

 

posted @   迷糊桃  阅读(506)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· C#/.NET/.NET Core优秀项目和框架2025年2月简报
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
· 【杭电多校比赛记录】2025“钉耙编程”中国大学生算法设计春季联赛(1)
点击右上角即可分享
微信分享提示