Java tutorial
/** * COPYRIGHT. Harry Wu 2010. ALL RIGHTS RESERVED. * Project: EasyPhoto * Author: Harry Wu <harrywu304@gmail.com> * Created On: Jun 28, 2008 5:12:21 PM * */ //package org.shaitu.easyphoto.util; import java.awt.Image; import java.awt.image.BufferedImage; import java.awt.image.ColorModel; import java.awt.image.IndexColorModel; import java.awt.image.WritableRaster; import java.io.File; import java.util.Iterator; import java.util.List; import javax.imageio.IIOImage; import javax.imageio.ImageIO; import javax.imageio.ImageTypeSpecifier; import javax.imageio.ImageWriteParam; import javax.imageio.ImageWriter; import javax.imageio.plugins.jpeg.JPEGImageWriteParam; import javax.imageio.stream.ImageOutputStream; import javax.swing.ImageIcon; /** * userful methods about image * @author harry */ public class ImageUtil { public final static String JPEG = "jpeg"; public final static String JPG = "jpg"; public final static String BMP = "bmp"; public final static String PNG = "png"; public final static String GIF = "gif"; public final static String TIFF = "tiff"; public final static String TIF = "tif"; /** * store BufferedImage to file * @param image BufferedImage * @param outputFile output image file * @param quality quality of output image * @return true success, else fail */ public static boolean storeImage(BufferedImage image, File outputFile, float quality) { try { //reconstruct folder structure for image file output if (outputFile.getParentFile() != null && !outputFile.getParentFile().exists()) { outputFile.getParentFile().mkdirs(); } if (outputFile.exists()) { outputFile.delete(); } //get image file suffix String extName = "png"; //get registry ImageWriter for specified image suffix Iterator writers = ImageIO.getImageWritersByFormatName(extName); ImageWriter imageWriter = (ImageWriter) writers.next(); //set image output params ImageWriteParam params = new JPEGImageWriteParam(null); params.setCompressionMode(ImageWriteParam.MODE_EXPLICIT); params.setCompressionQuality(quality); params.setProgressiveMode(javax.imageio.ImageWriteParam.MODE_DISABLED); params.setDestinationType(new ImageTypeSpecifier(IndexColorModel.getRGBdefault(), IndexColorModel.getRGBdefault().createCompatibleSampleModel(16, 16))); //writer image to file ImageOutputStream imageOutputStream = ImageIO.createImageOutputStream(outputFile); imageWriter.setOutput(imageOutputStream); imageWriter.write(null, new IIOImage(image, null, null), params); imageOutputStream.close(); imageWriter.dispose(); return true; } catch (Exception e) { e.printStackTrace(); } return false; } }