2

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?

Olaf Kock
  • 46,930
  • 8
  • 59
  • 90
lch
  • 2,028
  • 2
  • 25
  • 46
  • My guess is that this conversion may not be possible (not supported) using Apache Commons Imaging. Are you open to other alternatives? What are your project constraints? – hfontanez Oct 14 '20 at 16:19
  • 1
    I just need a library that does the conversion and works on open-jdk (I'm on 8 right now) I'm trying to figure out if Apache Commons Imaging can do that, but apparently it doesn't. So whatever works is ok (except for JAI) – lch Oct 14 '20 at 16:27
  • 1
    Apache Commons Imaging has [no write support for JPEG](http://commons.apache.org/proper/commons-imaging/formatsupport.html). – Olivier Oct 14 '20 at 18:33

1 Answers1

3

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"));
Haim Sulam
  • 316
  • 1
  • 5
  • 2
    Thank you! It works! However I had to install this plugin to read the tiff image with ImageIO: https://github.com/haraldk/TwelveMonkeys – lch Oct 17 '20 at 18:37