辨别图片类型

辨别图片类型

JPG图片头信息:FFD8FF
PNG图片头信息:89504E47
GIF图片头信息:47494638
BMP图片头信息:424D
 

工具代码

/**
	 * 获取图片类型
	 * JPG图片头信息:FFD8FF
	 * PNG图片头信息:89504E47
	 * GIF图片头信息:47494638
	 * BMP图片头信息:424D
	 * 
	 * @param is 图片文件流
	 * @return 图片类型:jpg|png|gif|bmp
	 */
	public static String getImageType(InputStream is) {
		String type = null;
		if (is != null) {
			byte[] b = new byte[4];
			try {
				is.read(b, 0, b.length);
			} catch (IOException e) {
				e.printStackTrace();
			}
			String hexStr = HexConverter.byteArrayToHexString(b, true);//图片文件流前4个字节的头信息(子文字母)
			if (hexStr != null) {
				if (hexStr.startsWith(JPG_HEX)) {
					type = JPG;
				} else if (hexStr.startsWith(PNG_HEX)) {
					type = PNG;
				} else if (hexStr.startsWith(GIF_HEX)) {
					type = GIF;
				} else if (hexStr.startsWith(BMP_HEX)) {
					type = BMP;
				}
			}
		}
		return type;
	}
	
	/**
	 * 获取图片类型
	 * JPG图片头信息:FFD8FF
	 * PNG图片头信息:89504E47
	 * GIF图片头信息:47494638
	 * BMP图片头信息:424D
	 * 
	 * @param file 图片文件
	 * @return 图片类型:jpg|png|gif|bmp
	 * @throws FileNotFoundException 未找到文件
	 */
	public static String getImageType(File file) throws FileNotFoundException {
		return getImageType(new FileInputStream(file));
	}

测试代码

 

/**
	 * 测试获取图片类型
	 * @throws FileNotFoundException 
	 */
	@Test
	public void testGetImageType() throws FileNotFoundException {
		String imageName = "simple.jpg";
		String srcPath = IMAGE_PATH + imageName;
		Assert.assertEquals(ImageUtil.JPG, ImageUtil.getImageType(new FileInputStream(srcPath)));
		
		imageName = "bd_logo1.png";
		srcPath = IMAGE_PATH + imageName;
		Assert.assertEquals(ImageUtil.PNG, ImageUtil.getImageType(new File(srcPath)));
	}

完整源码:https://github.com/ConstXiong/xtools

 


【Java面试题与答案】整理推荐

 

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值