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))); } }
本文来自博客园,作者:迷糊桃,转载请注明原文链接:https://www.cnblogs.com/mihutao/p/17863917.html
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· C#/.NET/.NET Core优秀项目和框架2025年2月简报
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
· 【杭电多校比赛记录】2025“钉耙编程”中国大学生算法设计春季联赛(1)