14

recently i'm facing problem when try to display an image file. Unfortunately, the image format is TIFF format which not supported by major web browser (as i know only Safari support this format). Due to certain constraint, i have to convert this format to others format that supported by major browser. However, it bring a lots of problem for me when i try to converting the format.

I had search through the web and although there been posted similar issue in this link How do I convert a TIF to PNG in Java?" but i can't have the result as it proposed..

Therefore i raise this Question again to wish that can have better explanation and guideline from you all..

There were few issue i'm faced during go through with the solution that proposed:

1) According to the answer that proposed by Jonathan Feinberg, it need to install JAI and JAI/ImageIO. However, after i installed both of them i still couldn't import the file in Netbean 7.2. NetBean 7.2 remain propose import default imageIO library.

2) when i'm using default ImageIO library Read method, it will return NULL value and i cannot continue to proceed.

3) I also tried others method such as convert TIFF file to BIN File by using BufferedOutputStream method but the result file is greater than 11 MB which is too large to load and end up loading failed.

 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();
            }
        }

Hence, hope that can get help and advise from you all so that i can convert TIFF format to other format such as JPEG/PNG.

Community
  • 1
  • 1
jc88
  • 471
  • 1
  • 5
  • 12
  • Tak a look at ImageMagic (http://www.imagemagick.org/script/index.php). Here is the java intrface for ImageMagic (http://www.jmagick.org/index.html) – pepuch Mar 15 '13 at 09:44
  • 1
    is it similar to the ImageMagick that proposed in [link](http://stackoverflow.com/questions/2291358/how-do-i-convert-a-tif-to-png-in-java) i tried the method that proposed in that post by using ImageMagick, but it failed to proceed when come to `ConvertCmd convert = new ConvertCmd();` – jc88 Mar 15 '13 at 10:03

5 Answers5

17

Had gone through some study and testing, found a method to convert TIFF to JPEG and sorry for pending so long only uploaded this answer.

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 is the path that you would like to store your JPEG image. For example: "C:/image/abc.JPG";
inFile is the input file which is the TIFF file

At least this method is workable to me. If there is any other better method, kindly share along with us.

EDIT: Just want to point out an editing in order to handle multipage tiff. Obviously you also have to handle the different names for the resulting images:

for (int page = 0; page < dec.getNumPages(); page++) { 
    RenderedImage op = dec.decodeAsRenderedImage(page );
    ...
}
Andrea
  • 6,032
  • 2
  • 28
  • 55
jc88
  • 471
  • 1
  • 5
  • 12
  • 2
    You can get the required jar from here: https://repository.jboss.org/nexus/content/repositories/thirdparty-releases/com/sun/media/jai-codec/1.1.3/jai-codec-1.1.3.jar – Elhanan Mishraky Sep 10 '14 at 09:46
  • This works fine for small images, like I tried with an image of 5.7 KB and is OK, but then tried with an image of 80 KB and I get java.lang.IndexOutOfBoundsException. Any help? – Roberto Rodriguez May 17 '17 at 16:38
  • getting Error Cannot instantiate the type JPEGEncodeParam – Ritter7 Jul 29 '19 at 12:09
9
  1. Add dependency

     <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. Coding

    final BufferedImage tif = ImageIO.read(new File("test.tif"));
    ImageIO.write(tif, "png", new File("test.png"));
    
Senjuti Mahapatra
  • 2,570
  • 4
  • 27
  • 38
Tk Yoon
  • 91
  • 1
  • 2
  • 1
    What about Multi-pages Tif files? can you use this lib with tif that have more than one page? can you share some code? thanks. – delkant Dec 05 '16 at 11:55
7

In case of many pages, working following:

  1. add dependency:

    <dependency>
        <groupId>com.github.jai-imageio</groupId>
        <artifactId>jai-imageio-core</artifactId>
        <version>1.4.0</version>
    </dependency>
    
  2. use following Java8 code

    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();
    }
    }
    
Alexey Alexeenka
  • 891
  • 12
  • 15
  • I get `javax.imageio.IIOException: 16-bit samples are not supported for Horizontal differencing Predictor` from this :( – beruic Jul 12 '19 at 13:18
1

If your target is Android, you could try this great Java library on Github that provides many utilities for handling, opening, and writing .tiff files.

A simple example from that Git showng how to convert TIFF to 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);
DarkCygnus
  • 7,420
  • 4
  • 36
  • 59
  • What if he is not on Android? The library you suggest uses native Android libraries. – beruic Jul 12 '19 at 12:45
  • 2
    Indeed, my suggestion works for Android. Included it here because I spent many time searching for a library and wanted to share it in case someone needed it. I'll clarify that it's for Android. Thanks for the.. feedback :) – DarkCygnus Jul 12 '19 at 12:58
  • 1
    +1 Thanks for making a answer that helps android developers. Since this issue is probably more needed for mobile then it is for desktop. – Bored915 Sep 20 '20 at 10:02
0

First, take a look to What is the best java image processing library/approach?. For your code you can use

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

like you can see in write an image to file example.

Community
  • 1
  • 1
Mihai8
  • 3,113
  • 1
  • 21
  • 31
  • i been tried the example from **MKYong** but when come it ImageIO.Read, it return me null cause not able to read TIF format..if i read JPG and PNG there will not an issue..everything gone smooth but just when try to read TIFF format.. – jc88 Mar 15 '13 at 09:58
  • See http://stackoverflow.com/questions/2898311/reading-and-writing-out-tiff-image-in-java, it might be useful. – Mihai8 Mar 15 '13 at 10:02
  • Thanks for your suggestion, i failed to add JAI jar although i already include in my CLASSPATH but still not able to import it..can you provide me more information regarding how to include JAI jar? very appreciate with you help – jc88 Mar 15 '13 at 10:06
  • After some time struggle in JAI and finally i'm able work with it..unfortunately, it will prompt me an error which i have no clue on it. **java.lang.NoClassDefFoundError: Could not initialize class javax.media.jai.JAI**..i have search through the web and most said that it is beside Server not able to find JAI library. But i'm sure that has added in the JAI file. Do you have any idea on this error? – jc88 Mar 22 '13 at 01:19
  • AFAIK, JAI namespace is now blacklisted in Java 8. – ActiveTrayPrntrTagDataStrDrvr Jun 12 '14 at 09:04