项目背景
在项目中希望实现对于TIF的Thumbnail的获取,但是如果在获取TIF文件后实时生成,性能方面较差。因此我采用的方案是文件获取一次,生成Thumbnail塞入TIF文件中,以提高性能那个。
功能条件:
使用开源项目:
GitHub:
<dependency>
<groupId>net.coobird</groupId>
<artifactId>thumbnailator</artifactId>
<version>0.4.8</version>
</dependency>
实现方式:
public Boolean generateThumbnailsIntoFile(String fileName) throws Exception {
Boolean result = false;
;
try {
Tiff newTiff = new Tiff(fileToBytes(fileName));
int pageCount = newTiff.getPageCount();
for (int i = 0; i < pageCount; i++) {
byte[] page = newTiff.getPage(i);
if (hasThumnails(page)) {
continue;
}
byte[] thumbnail = createThumbnailFile(page, newTiff.getFileName(i));
newTiff.putThumbnail(i, thumbnail);
}
// replace the sourceFile
bytesToFile(newTiff.toByteArray(), fileName);
result = true;
} catch (Exception e) {
throw e;
}
return result;
}
public static byte[] fileToBytes(String filePath) throws Exception {
byte[] buffer = null;
File file = new File(filePath);
FileInputStream fis = new FileInputStream(file);
ByteArrayOutputStream bos = new ByteArrayOutputStream();
byte[] b = new byte[1024];
int n;
while ((n = fis.read(b)) != -1) {
bos.write(b, 0, n);
}
buffer = bos.toByteArray();
if (null != bos) {
bos.close();
}
if (null != fis) {
fis.close();
}
return buffer;
}
public Boolean hasThumnails(byte[] pageData) {
if (pageData != null) {
return thumbnailsFormate(pageData);
}
return false;
}
public byte[] createThumbnailFile(byte[] page, String fileName) throws IOException {
log.info("createThumbnailFile file name: " + fileName + " page=null:" + (page == null ? true : false));
ImageIO.scanForPlugins();
ByteArrayInputStream in = new ByteArrayInputStream(page);
ByteArrayOutputStream out = new ByteArrayOutputStream();
BufferedImage originalImage = ImageIO.read(in);
Thumbnails.of(originalImage).size(200, 220).imageType(BufferedImage.TYPE_INT_RGB).outputQuality(0.5f)
.keepAspectRatio(false).outputFormat("jpg").toOutputStream(out);
return out.toByteArray();
}