Create image thumbnail in java using ImageJ API

For more information on how to implement Photos sharing website using Java, Spring, Tomcat, Imagej download Fotovault (opensource Photo sharing project) Fotovault - Photo Sharing Project
 
Below is the code example to create thumbnails in Java.

Download ImageJ jar from

http://rsbweb.nih.gov/ij/download.html

and include it in your classpath.

The below code example proportionately/evenly crops the image to make the image a perfect square and creates a thumbnail of 100 X 100 pixels.
cropAndResize method takes the fileAbsolutePath and Save as image suffix (thumbnail name suffix).


private String cropAndResize(String fileAbsolutePath, String fileSaveAsNameSuffix) {
        try {
            Opener opener = new Opener();
            ImagePlus imp = opener.openImage(fileAbsolutePath);
            ImageProcessor ip = imp.getProcessor();
            StackProcessor sp = new StackProcessor(imp.getStack(), ip);
           
            int width = imp.getWidth();
            int height = imp.getHeight();
           
            int cropWidth = 0;
            int cropHeight = 0;
           
            if(width > height) {
                cropWidth = height;
                cropHeight = height;
            } else {
                cropWidth = width;
                cropHeight = width;
            }
           
            int x = -1;
            int y = -1;
           
            if(width == height) {
                x = 0;
                y = 0;
            } else if(width > height) {
                x = (width - height) / 2;
                y=0;
            } else if (width < height) {
                x = 0;
                y = (height - width) / 2;
            }
             
            logger.debug(imp.getWidth());
            logger.debug(imp.getHeight());
            logger.debug("cropWidth " + cropWidth);
            logger.debug("cropHeight" + cropHeight);
           
            ImageStack croppedStack = sp.crop(x, y, cropWidth, cropHeight);
           
            imp.setStack(null, croppedStack);
           
            logger.debug(imp.getWidth());
            logger.debug(imp.getHeight());
           
            sp = new StackProcessor(imp.getStack(), imp.getProcessor());
           
            ImageStack resizedStack = sp.resize(100, 100, true);
            imp.setStack(null, resizedStack);
            StringBuffer filePath = new StringBuffer(fileAbsolutePath);
            filePath.replace(filePath.lastIndexOf("."),
            filePath.lastIndexOf("."), fileSaveAsNameSuffix);
            String saveAsFilePath = filePath.toString();
            IJ.save(imp, saveAsFilePath);
            return saveAsFilePath;
        } catch (Exception e) {
            logger.error("Error while resizing Image.");
            e.printStackTrace();
            return null;
        }
}


Comments