import java.awt.RenderingHints;
import java.awt.image.renderable.ParameterBlock;
import java.io.InputStream;
import java.io.OutputStream;

import javax.media.jai.JAI;
import javax.media.jai.OpImage;
import javax.media.jai.RenderedOp;

import com.sun.media.jai.codec.SeekableStream;

public abstract class ImageUtil {
	
    private static final String JAI_STREAM_ACTION = "stream";
    private static final String JAI_SUBSAMPLE_AVERAGE_ACTION = "SubsampleAverage";
    private static final String JAI_ENCODE_ACTION = "encode";

    public enum EncodeFormat { JPEG, PNG };

	public static void resize(InputStream source, OutputStream destination, Integer maxWidth, Integer maxHeight, EncodeFormat encodeFormat) {
		
		SeekableStream s = SeekableStream.wrapInputStream(source, true);
		
		try {
			RenderedOp image = JAI.create(JAI_STREAM_ACTION, s);
			((OpImage) image.getRendering()).setTileCache(null);
	
			if (maxWidth == null || maxWidth <= 0) maxWidth = image.getWidth();
			if (maxHeight == null || maxHeight <= 0) maxHeight = image.getHeight();
			
			if (maxWidth > image.getWidth()) maxWidth = image.getWidth();
			if (maxHeight > image.getHeight()) maxHeight = image.getHeight();
			
			double hRatio = ((double) maxHeight) / ((double) image.getHeight());
			double wRatio = ((double) maxWidth) / ((double) image.getWidth());
			double scale = Math.min(hRatio, wRatio);
			
			ParameterBlock pb = new ParameterBlock();
			pb.addSource(image); // The source image
			pb.add(scale);          // The xScale
			pb.add(scale);          // The yScale
			pb.add(0.0F);           // The x translation
			pb.add(0.0F);           // The y translation
	
			RenderingHints qualityHints = new RenderingHints(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
	
			RenderedOp resizedImage = JAI.create(JAI_SUBSAMPLE_AVERAGE_ACTION, pb, qualityHints);
	
			JAI.create(JAI_ENCODE_ACTION, resizedImage, destination, encodeFormat.name(), null);
		}
		finally {
			try { s.close(); }
			catch (Exception ignore) {}
		}
	}
}

Add a code snippet to your website: www.paste.org