Tuesday, January 10, 2012

Image Resizer

package com.nmmc.dms.utils.compression;

import java.awt.AlphaComposite;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Locale;

import javax.imageio.IIOImage;
import javax.imageio.ImageIO;
import javax.imageio.ImageWriteParam;
import javax.imageio.ImageWriter;
import javax.imageio.plugins.jpeg.JPEGImageWriteParam;
import javax.imageio.stream.ImageOutputStream;

import org.apache.commons.io.FileUtils;
import org.apache.commons.lang.RandomStringUtils;
import org.apache.commons.lang.math.RandomUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

public class ImageResizer {

    private static Log log1 = LogFactory.getLog(ImageResizer.class);

    private static int MAX_PHOTO_WIDTH = 500;

    private static int MAX_PHOTO_HEIGHT = 500;

    public static HashMap createResizedCopy(InputStream inputStream, boolean blnResize) throws IOException {
        boolean preserveAlpha = true;
        HashMap<String, Object> hstKeys = new HashMap<String, Object>();
        BufferedImage originalImage = ImageIO.read(inputStream);

        int imageType = preserveAlpha ? BufferedImage.TYPE_INT_RGB : BufferedImage.TYPE_INT_ARGB;

        int width = originalImage.getWidth();
        int height = originalImage.getHeight();

        if (blnResize) {
            double h = new Double(originalImage.getHeight()).doubleValue();
            double w = new Double(originalImage.getWidth()).doubleValue();
            double ratio = h / w;
            double defaultRatio = new Double(MAX_PHOTO_HEIGHT).doubleValue() / new Double(MAX_PHOTO_WIDTH).doubleValue();
            if (ratio > defaultRatio) {
                height = MAX_PHOTO_HEIGHT;
                width = new Double(new Double(MAX_PHOTO_HEIGHT).doubleValue() / new Double(ratio).doubleValue()).intValue();
            } else {
                height = new Double(new Double(MAX_PHOTO_WIDTH).doubleValue() * new Double(ratio).doubleValue()).intValue();
                width = MAX_PHOTO_WIDTH;
            }
        }
        BufferedImage resizedImage = new BufferedImage(width, height, imageType);
        Graphics2D g = resizedImage.createGraphics();
        g.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BICUBIC);
        if (preserveAlpha)
            g.setComposite(AlphaComposite.Src);
        g.drawImage(originalImage, 0, 0, width, height, null);
        g.dispose();

        ImageWriter writer = null;
        Iterator iter = ImageIO.getImageWritersByFormatName("jpg");
        if (iter.hasNext()) {
            writer = (ImageWriter) iter.next();
        }

        File outputfile = File.createTempFile(RandomStringUtils.randomAlphanumeric(6) + "" + RandomUtils.nextInt(), ".jpg");

        // Prepare output file
        ImageOutputStream ios = ImageIO.createImageOutputStream(outputfile);
        writer.setOutput(ios);

        // Set the compression quality
        ImageWriteParam iwparam = new JPEGImageWriteParam(Locale.getDefault());
        iwparam.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
        iwparam.setCompressionQuality(0.2f);

        // Write the image
        writer.write(null, new IIOImage(resizedImage, null, null), iwparam);

        // Cleanup
        ios.flush();
        writer.dispose();
        ios.close();

        byte bytes[] = FileUtils.readFileToByteArray(outputfile);
        hstKeys.put("Width", resizedImage.getWidth());
        hstKeys.put("Height", resizedImage.getHeight());
        hstKeys.put("DATA", bytes);
        hstKeys.put("Length", bytes.length);
        outputfile.delete();
        return hstKeys;
    }

}