辨别图片类型

版权声明:转载请注名出处 https://blog.csdn.net/meism5/article/details/88387800

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

猜你喜欢

转载自blog.csdn.net/meism5/article/details/88387800