Optimizing images using ImageJ

In this quick tip I’ll show how to optimise images on the fly using ImageJ, looks simple but it took some time because of the input stream creation after the optimisation. I googled it but all the codes that I found were producing empty OutputStreams, until I finally realise that I could use ImageIO to produce the correct ImageWriter and ImageOutputStream.

public InputStream createOptimizedImage(Rendition rendition) throws IOException {
      try {
         final InputStream renditionInputStream = getRenditionInputStream(rendition);
         final BufferedImage bufferedImage = ImageIO.read(renditionInputStream);

         final String imageTitle = rendition.getName();
         final ImagePlus image = new ImagePlus(imageTitle, bufferedImage);

         final ImageProcessor processor = image.getProcessor();
         processor.setInterpolationMethod(ImageProcessor.BILINEAR);

         final BufferedImage optimizedImage = processor.getBufferedImage();

         final ImageWriter writer = ImageIO.getImageWritersByMIMEType(rendition.getMimeType()).next();

         final InputStream optimizedImageIs = getOptimizedImageInputStream(optimizedImage, writer);
         return optimizedImageIs;

      } catch (IOException e) {
         LOG.error("Failed in creating optimized image ", e);
         throw e;
      }
   }

   private InputStream getOptimizedImageInputStream(final BufferedImage optimizedImage, final ImageWriter writer) throws IOException {
      final ByteArrayOutputStream os = new ByteArrayOutputStream();
      final ImageOutputStream stream = ImageIO.createImageOutputStream(os);
      writer.setOutput(stream);
      writer.write(optimizedImage);
      writer.dispose();
      stream.close();

      return new ByteArrayInputStream(os.toByteArray());
   }

Forget about Rendition I wrote this code to be used into Adobe AEM, you can replace getRenditionInputStream to anything that returns an InputStream.

Since I used maven, this is the necessary dependency

<!-- ImageJ -->
<dependency>
   <groupId>net.imagej</groupId>
   <artifactId>ij</artifactId>
   <version>1.51h</version>
</dependency>

And the repository

<repository>
   <id>imagej.public</id>
   <url>http://maven.imagej.net/content/groups/public</url>
</repository>

Enjoy.

Allan de Queiroz

Allan de Queiroz
London based software engineer

XServer forward from Linux text mode for Headless purposes.

Hello, this post is about XServer forward from Linux text mode, **not ssh forward, anything related to VNC** or things like that.Recently...… Continue reading