图像处理 -Java-TIFF 转换 JPG
作者:alexgaoyh
- 2024-02-01 河南
本文字数:1628 字
阅读完需:约 5 分钟
背景
《图像处理-Java-TIFF 转换 JPG》,之前在编写过关于图像边缘检测-去黑边、图像边缘检测-自动纠偏、图像处理-锐化、图像处理-去噪/高斯模糊/套红、图像处理-背景色平滑/反色、图像处理-指定大小压缩等一系列文章,接下来主要介绍 TIFF 格式的图像处理。
概述
使用 JAVA 语言实现,将给定的 TIF 格式的图像转换为 JPG,其中 TIF 格式的图像有两种,一种是未经过压缩的,另一种是经过 LZW 压缩的。本文提供两个函数对其进行分别处理。
代码实现
// dependency com.twelvemonkeys.imageio.imageio-tiff.3.10.1 handle no-LZW compress TIF file
public static void tiffToJpg(String tiffFilePath, String jpgFilePath) throws IOException, InterruptedException {
ImageReader reader = ImageIO.getImageReadersByFormatName("TIF").next();
ImageInputStream imageInputStream = new FileImageInputStream(new File(tiffFilePath));
reader.setInput(imageInputStream);
ImageWriter writer = ImageIO.getImageWritersByFormatName("JPEG").next();
ImageOutputStream imageOutputStream = ImageIO.createImageOutputStream(new File(jpgFilePath));
writer.setOutput(imageOutputStream);
ImageWriteParam param = writer.getDefaultWriteParam();
param.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
param.setCompressionQuality(0.8f); // adjust the quality as needed
int numImages = reader.getNumImages(true);
int availableProcessors = Runtime.getRuntime().availableProcessors();
ExecutorService executorService = Executors.newFixedThreadPool(availableProcessors);
for (int i = 0; i < numImages; i++) {
final int imageIndex = i;
executorService.submit(() -> {
try {
BufferedImage image = reader.read(imageIndex);
byte[] imageData = extractImageData(image);
synchronized (writer) {
writer.write(null, new javax.imageio.IIOImage(image, null, null), param);
}
} catch (IOException e) {
e.printStackTrace();
}
});
}
executorService.shutdown();
executorService.awaitTermination(Long.MAX_VALUE, TimeUnit.NANOSECONDS);
reader.dispose();
writer.dispose();
imageInputStream.close();
imageOutputStream.close();
}
private static byte[] extractImageData(BufferedImage image) {
Raster raster = image.getData();
DataBufferByte dataBuffer = (DataBufferByte) raster.getDataBuffer();
return dataBuffer.getData();
}
// dependency org.apache.commons.commons-imaging.1.0-alpha3 handle LZW compress TIF file
public static void tiffToJpg2(String inputFilePath, String outputFilePath) throws IOException {
try {
File inputFile = new File(inputFilePath);
TiffImageParser parser = new TiffImageParser();
BufferedImage image = Imaging.getBufferedImage(new FileInputStream(inputFile), null);
File outputFile = new File(outputFilePath);
ImageIO.write(image, "jpg", outputFile);
} catch (ImageReadException | IOException e) {
e.printStackTrace();
}
}
复制代码
参考
划线
评论
复制
发布于: 刚刚阅读数: 3
版权声明: 本文为 InfoQ 作者【alexgaoyh】的原创文章。
原文链接:【http://xie.infoq.cn/article/43e7aae7f06a77f5e320a45ea】。
本文遵守【CC-BY 4.0】协议,转载请保留原文出处及本版权声明。
alexgaoyh
关注
DevOps 2013-12-08 加入
https://gitee.com/alexgaoyh
评论