【问题标题】:How to convert TIFF to JPEG/PNG in java如何在 Java 中将 TIFF 转换为 JPEG/PNG
【发布时间】:2013-03-03 23:12:44
【问题描述】:

最近我在尝试显示图像文件时遇到了问题。不幸的是,图像格式是主要网络浏览器不支持的 TIFF 格式(据我所知,只有 Safari 支持这种格式)。由于某些限制,我必须将此格式转换为主流浏览器支持的其他格式。但是,当我尝试转换格式时,它给我带来了很多问题。

我在网上搜索过,虽然在此链接 How do I convert a TIF to PNG in Java?" 中发布了类似的问题,但我无法得到它建议的结果..

因此,我再次提出这个问题,希望大家能得到更好的解释和指导..

在实施所提出的解决方案时,我遇到的问题很少:

1)根据Jonathan Feinberg提出的答案,需要安装JAI和JAI/ImageIO。 但是,在我安装了它们之后,我仍然无法在 Netbean 7.2 中导入文件。 NetBean 7.2 仍然建议导入默认 imageIO 库。

2) 当我使用默认 ImageIO 库读取方法时,它将返回 NULL 值,我无法继续。

3) 我也尝试了其他方法,例如使用 BufferedOutputStream 方法将 TIFF 文件转换为 BIN 文件,但结果文件大于 11 MB,太大而无法加载并最终加载失败。

 if (this.selectedDO != null) {
        String tempDO = this.selectedDO.DONo;
        String inPath = "J:\\" + tempDO + ".TIF";
        String otPath = "J:\\" + tempDO + ".bin";

        File opFile = new File(otPath);

        File inFile = new File(inPath);

        BufferedInputStream input = null;
        BufferedOutputStream output = null;
        try {
            input = new BufferedInputStream(new FileInputStream(inPath), DEFAULT_BUFFER_SIZE);
            output = new BufferedOutputStream(new FileOutputStream(otPath), DEFAULT_BUFFER_SIZE);

            byte[] buffer = new byte[DEFAULT_BUFFER_SIZE];
            int length;
            while ((length = input.read(buffer)) > 0) {
                output.write(buffer, 0, length);
            }

        } finally {
            try {
                output.flush();
                output.close();
                input.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

因此,希望能得到大家的帮助和建议,以便我可以将 TIFF 格式转换为其他格式,例如 JPEG/PNG。

【问题讨论】:

标签: java image tiff jai


【解决方案1】:

经过一些研究和测试,找到了一种将 TIFF 转换为 JPEG 的方法,抱歉这么久才上传这个答案。

SeekableStream s = new FileSeekableStream(inFile);
TIFFDecodeParam param = null;
ImageDecoder dec = ImageCodec.createImageDecoder("tiff", s, param);
RenderedImage op = dec.decodeAsRenderedImage(0);

FileOutputStream fos = new FileOutputStream(otPath);
JPEGEncodeParam jpgparam = new JPEGEncodeParam();
jpgparam.setQuality(67);
ImageEncoder en = ImageCodec.createImageEncoder("jpeg", fos, jpgparam);
en.encode(op);
fos.flush();
fos.close();

otPath 是您希望存储 JPEG 图像的路径。 例如:"C:/image/abc.JPG";
inFile是输入文件,即TIFF文件

至少这种方法对我来说是可行的。如果有其他更好的方法,欢迎和我们一起分享。

【讨论】:

  • 您可以从这里获取所需的jar:repository.jboss.org/nexus/content/repositories/…
  • 这适用于小图像,例如我尝试使用 5.7 KB 的图像并且没问题,但随后尝试使用 80 KB 的图像,我得到 java.lang.IndexOutOfBoundsException。有什么帮助吗?
  • 出现错误无法实例化类型 JPEGEncodeParam
【解决方案2】:
  1. 添加依赖

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

https://mvnrepository.com/artifact/com.github.jai-imageio/jai-imageio-core

https://mvnrepository.com/artifact/com.github.jai-imageio/jai-imageio-core/1.3.1

  1. 编码

    final BufferedImage tif = ImageIO.read(new File("test.tif"));
    ImageIO.write(tif, "png", new File("test.png"));
    

【讨论】:

  • 多页 Tif 文件怎么样?您可以将此库与超过一页的 tif 一起使用吗?你能分享一些代码吗?谢谢。
【解决方案3】:

如果页面很多,请按照以下方式工作:

  1. 添加依赖:

    <dependency>
        <groupId>com.github.jai-imageio</groupId>
        <artifactId>jai-imageio-core</artifactId>
        <version>1.4.0</version>
    </dependency>
    
  2. 使用以下 Java8 代码

    public void convertTiffToPng(File file) {
    try {
        try (InputStream is = new FileInputStream(file)) {
            try (ImageInputStream imageInputStream = ImageIO.createImageInputStream(is)) {
                Iterator<ImageReader> iterator = ImageIO.getImageReaders(imageInputStream);
                if (iterator == null || !iterator.hasNext()) {
                    throw new RuntimeException("Image file format not supported by ImageIO: " + file.getAbsolutePath());
                }
    
    
                // We are just looking for the first reader compatible:
                ImageReader reader = iterator.next();
                reader.setInput(imageInputStream);
    
                int numPage = reader.getNumImages(true);
    
                // it uses to put new png files, close to original example n0_.tiff will be in /png/n0_0.png
                String name = FilenameUtils.getBaseName(file.getAbsolutePath()); 
                String parentFolder = file.getParentFile().getAbsolutePath();
    
                IntStream.range(0, numPage).forEach(v -> {
                    try {
                        final BufferedImage tiff = reader.read(v);
                        ImageIO.write(tiff, "png", new File(parentFolder + "/png/" + name + v + ".png"));
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                });
            }
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
    }
    

【讨论】:

  • 我从这里得到javax.imageio.IIOException: 16-bit samples are not supported for Horizontal differencing Predictor :(
【解决方案4】:

如果您的目标是 Android,您可以在 Github 上尝试 this great Java library,它提供了许多用于处理、打开和编写 .tiff 文件的实用程序。

Git 中的一个简单示例展示了如何将 TIFF 转换为 JPEG:

TiffConverter.ConverterOptions options = new TiffConverter.ConverterOptions();
//Set to true if you want use java exception mechanism
options.throwExceptions = false; 
//Available 128Mb for work
options.availableMemory = 128 * 1024 * 1024; 
//Number of tiff directory to convert;
options.readTiffDirectory = 1;         
//Convert to JPEG
TiffConverter.convertTiffJpg("in.tif", "out.jpg", options, progressListener);

【讨论】:

  • 如果他不在 Android 上怎么办?您建议的库使用原生 Android 库。
  • 确实,我的建议适用于 Android。将它包含在这里是因为我花了很多时间搜索图书馆并想分享它以防有人需要它。我会澄清它适用于Android。感谢您的反馈:)
  • +1 感谢您提供有助于 Android 开发人员的答案。由于移动设备可能比桌面更需要此问题。
【解决方案5】:

首先,看看What is the best java image processing library/approach?。对于您的代码,您可以使用

javax.imageio.ImageIO.write(im, type, represFile);

就像您在write an image to file example 中看到的那样。

【讨论】:

  • 我尝试了 MKYong 中的示例,但是当它来到 ImageIO.Read 时,它返回我 null 原因无法读取 TIF 格式..如果我在那里读取 JPG 和 PNG不会有问题..一切都很顺利,但只是在尝试读取 TIFF 格式时..
  • *.com/questions/2898311/…,它可能有用。
  • 感谢您的建议,尽管我已经包含在我的 CLASSPATH 中但仍然无法导入它,但我未能添加 JAI jar。您能否提供有关如何包含 JAI jar 的更多信息?非常感谢您的帮助
  • 在 JAI 中挣扎了一段时间后,我终于可以使用它了。不幸的是,它会提示我一个我不知道的错误。 java.lang.NoClassDefFoundError: Could not initialize class javax.media.jai.JAI..我在网上搜索过,大多数人说它在服务器旁边找不到 JAI 库。但我确定已在 JAI 文件中添加。您对此错误有任何想法吗?
  • AFAIK,JAI 命名空间现在在 Java 8 中被列入黑名单。