Android 读取文件头判断文件类型

private static String getImageType() {

		// File file = new File("C:/Users/Administrator/Desktop/111.png");
		// File file = new File("C:/Users/Administrator/Desktop/111.jpg");
		File file = new File("C:/Users/Administrator/Desktop/111.bmp");
		if (!file.exists()) {
			System.err.println("--- file not exists! ---");
			return null;
		}

		byte[] png_type = new byte[] { (byte) 0x89, (byte) 0x50, (byte) 0x4E,
				(byte) 0x47, (byte) 0x0D, (byte) 0x0A, (byte) 0x1A,
				(byte) 0x0A, '\0' };
		byte file_head[] = new byte[9];

		try {
			FileInputStream fis = new FileInputStream(file);
			fis.read(file_head, 0, 9);
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}

		file_head[8] = '\0';
		switch (file_head[0]) {
		case (byte) 0xff:
			if (file_head[1] == (byte) 0xd8)
				return "jpg";// jpeg
		case (byte) 0x42:
			if (file_head[1] == (byte) 0x4D)
				return "bmp";// bmp
		case (byte) 0x89:
			if (file_head[1] == png_type[1] && file_head[2] == png_type[2]
					&& file_head[3] == png_type[3]
					&& file_head[4] == png_type[4]
					&& file_head[5] == png_type[5]
					&& file_head[6] == png_type[6]
					&& file_head[7] == png_type[7])
				return "png";// png
		}

		return null;
	}


参考:http://blog.csdn.net/include1224/article/details/5195470


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值