一篓吁、TIF/TIFF介紹
引用百度百科的一句話總結(jié):
標(biāo)簽圖像文件格式(Tag Image File Format虹曙,簡寫為TIFF)是一種靈活的位圖格式卿堂,主要用來存儲包括照片和藝術(shù)圖在內(nèi)的圖像赊堪。
二碧注、轉(zhuǎn)換TIF所需要的jar包
需要3個jar包:
jai_core-1.1.3.jar
jai_imageio.jar
jai-codec-1.1.3.jar
下載地址請見文章在最底部。
三垫竞、使用Java轉(zhuǎn)成TIF格式的工具類
3.1 工具類介紹:
傳入文件的絕對路徑澎粟,返回的是一個TIF格式dpi為300的圖片路徑蛀序,dpi可以自己設(shè)置值。
其中有遇到圖片位深度為8位的圖片無法轉(zhuǎn)換活烙,所以多加了一個filterFilePath徐裸,用于過濾一次,統(tǒng)一轉(zhuǎn)換成位深度為24的JPG圖片啸盏,然后再進(jìn)行TIF編碼重贺。
3.2 工具類如下:
/**
*
* 功能描述: 圖片轉(zhuǎn)tif格式
*
* @param: [fileAbsolutePath]
* @return: java.lang.String 轉(zhuǎn)成TIF圖片的地址全路徑
* @auther: KevinZc
* @date: 2018/9/8 22:14
*/
public String image2Tif(String fileAbsolutePath){
OutputStream outputStream = null;
String filterFilePath = null;
String tifFilePath = null;
ImageOutputStream ios = null;
try {
// 解決位深度太小 start ====注意:8位深度的圖片會出現(xiàn)文件損壞問題
File picture = new File(fileAbsolutePath);
// 統(tǒng)一進(jìn)行一次過濾 轉(zhuǎn)換成24位深度
filterFilePath = fileAbsolutePath.substring(0, fileAbsolutePath.lastIndexOf("."))+".JPG";
tifFilePath = filterFilePath.substring(0, filterFilePath.lastIndexOf("."))+".tif";
ios = ImageIO.createImageOutputStream(new File(filterFilePath));
ImageIO.write(ImageIO.read(picture),"JPG", ios);
// 解決位深度太小 end
FileSeekableStream stream = new FileSeekableStream(filterFilePath);
PlanarImage in = JAI.create("stream", stream);
OutputStream os = null;
os = new FileOutputStream(tifFilePath);
// 設(shè)置dpi為300
TIFFEncodeParam param = new TIFFEncodeParam();
param.setCompression(TIFFEncodeParam.COMPRESSION_NONE);
TIFFField[] extras = new TIFFField[2];
extras[0] = new TIFFField(282, TIFFTag.TIFF_RATIONAL, 1, (Object) new long[][]{{(long) 300, 1}, {0, 0}});
// extras[0] = new TIFFField(282, TIFFTag.TIFF_RATIONAL, 1, (Object) new long[][]{{(long) dpi, 1}, {0, 0}});
extras[1] = new TIFFField(283, TIFFTag.TIFF_RATIONAL, 1, (Object) new long[][]{{(long) 300, 1}, {0, 0}});
param.setExtraFields(extras);
TIFFImageEncoder enc = new TIFFImageEncoder(os, param);
try {
enc.encode(in);
os.flush();
os.close();
stream.close();
} catch (Exception e) {
logger.error("{}",e );
throw new RuntimeException(e);
}
return tifFilePath;
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (outputStream != null) {
outputStream.close();
}
if (ios != null) {
ios.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
四、踩坑點
- jar包難找回懦,到處都收費(fèi)气笙;解決辦法:見本文底部
- 8位深度的圖片會出現(xiàn)文件損壞問題;解決辦法:中轉(zhuǎn)一次怯晕,統(tǒng)一轉(zhuǎn)成24位深度的JPG圖片
- 在下載TIF圖片后無法刪除產(chǎn)生的臨時文件潜圃,RenderedOp資源被占用無法刪除問題;解決辦法:見上面工具類
github地址:圖片轉(zhuǎn)TIFF格式工具類源碼及jar包