Java中处理tiff文件

java中处理tiff格式文件

添加依赖

 <dependency>
     <groupId>com.github.jai-imageio</groupId>
     <artifactId>jai-imageio-core</artifactId>
     <version>1.4.0</version>
</dependency>

<dependency>
    <groupId>com.drewnoakes</groupId>
    <artifactId>metadata-extractor</artifactId>
    <version>2.8.1</version>
</dependency>

判断tiff格式工具类

public static boolean checkImageBase64Format(String filePath) {
	byte[] data = null;
	try {
		InputStream in = new FileInputStream(filePath);
		data = new byte[in.available()];
		in.read(data);
		in.close();
		byte[] b = java.util.Base64.getDecoder().decode(new String(Base64.encodeBase64(data)));
		// 	判断是否为tiff格式
		if ((b[0] & 0xFF) == 0x49 && (b[1] & 0xFF) == 0x49 && (b[2] & 0xFF) == 0x2A) {
			return true;
		} else {
			return false;
		}
	} catch (Exception e) {
		e.printStackTrace();
		return false;
	}
}

转换为其他格式图片

public static void tiffToJpg(String oldPath, String newPath) {
	try {
		BufferedImage bufferegImage = ImageIO.read(new File(oldPath));
		ImageIO.write(bufferegImage, "png", new File(newPath));
	} catch (IOException e) {
		e.printStackTrace();
	}
}

必须要添加 jai-imageio-core 依赖

不添加该依赖ImageIO.read()方法无法读取tiff格式图片信息

String[] writerFileSuffixes = ImageIO.getWriterFileSuffixes();
该原生方法只支持jpg,bmp,gif,png,jpeg,wbmp格式

添加依赖后则支持jpg,tiff,pcx,bmp,gif,png,raw,ppm,tif,pgm,wbmp,jpeg,pbm

Tiff格式详细信息读取方法

File file = new File(filePath);
Metadata metadata = TiffMetadataReader.readMetadata(file);
if (null != metadata.getDirectories()) {
	Iterable<Directory> a = metadata.getDirectories();
	for (Directory directory : a) {
		Iterator<Tag> tag = directory.getTags().iterator();
		while (tag.hasNext()) {
			Tag tagInfo = tag.next();
			if ("Image Width".equals(tagInfo.getTagName())) {
				result.put("width", Long.valueOf(tagInfo.getDescription().substring(0, (tagInfo.getDescription().lastIndexOf("pixels") - 1))));
			} else if ("Image Height".equals(tagInfo.getTagName())) {
				result.put("height", Long.valueOf(tagInfo.getDescription().substring(0, (tagInfo.getDescription().lastIndexOf("pixels") - 1))));
			}
		}
	}
}
  • 4
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 3
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值