Search code examples
javaapache-commonsapache-commons-imaging

Apache Commons Imaging - convert tiff to jpg


I need to convert a tiff image into a jpg one using Apache Commons Imaging. I tried to but I can't figure out how to do it using this library.

final BufferedImage image = Imaging.getBufferedImage(new File(image));
final ImageFormat format = ImageFormats.JPEG;
final Map<String, Object> params = new HashMap<>();
return Imaging.writeImageToBytes(image, format, params);

Where image is my tiff file to be converted, but I get

org.apache.commons.imaging.ImageWriteException: This image format (Jpeg-Custom) cannot be written.

I don't understand what I'm doing wrong could someone help?


Solution

  • Try the use of java AWT:

       import java.awt.Color;
       import java.awt.image.BufferedImage;
       import java.io.File;
       import java.io.IOException;
       import javax.imageio.ImageIO;
    

    And code:

      // TIFF image file read
      BufferedImage tiffImage = ImageIO.read(new File("tiff-image.tiff"));
      // Prepare the image before writing - with same dimensions
      BufferedImage jpegImage = new BufferedImage(
              tiffImage.getWidth(),
              tiffImage.getHeight(), 
              BufferedImage.TYPE_INT_RGB);
      // Draw image from original TIFF to the new JPEG image
      jpegImage.createGraphics().drawImage(tiffImage, 0, 0, Color.WHITE, null);
      // Write the image as JPEG to disk
      ImageIO.write(jpegImage, "jpg", new File("jpeg-image.jpg"));