- package com.itcast.utils;
- import java.awt.Color;
- import java.awt.Component;
- import java.awt.Graphics;
- import java.awt.Graphics2D;
- import java.awt.Image;
- import java.awt.MediaTracker;
- import java.awt.Toolkit;
- import java.awt.p_w_picpath.BufferedImage;
- import java.awt.p_w_picpath.ConvolveOp;
- import java.awt.p_w_picpath.Kernel;
- import java.io.ByteArrayOutputStream;
- import java.io.File;
- import java.io.FileInputStream;
- import java.io.FileOutputStream;
- import java.io.IOException;
- import java.io.OutputStream;
- import javax.p_w_picpathio.ImageIO;
- import javax.swing.ImageIcon;
- import com.sun.p_w_picpath.codec.jpeg.JPEGCodec;
- import com.sun.p_w_picpath.codec.jpeg.JPEGEncodeParam;
- import com.sun.p_w_picpath.codec.jpeg.JPEGImageEncoder;
- /**
- * 图像压缩工具
- * @author lihuoming@sohu.com
- *
- */
- public class ImageSizer {
- public static final MediaTracker tracker = new MediaTracker(new Component() {
- private static final long serialVersionUID = 1234162663955668507L;}
- );
- /**
- * @param originalFile 原图像
- * @param resizedFile 压缩后的图像
- * @param width 图像宽
- * @param format 图片格式 jpg, png, gif(非动画)
- * @throws IOException
- */
- public static void resize(File originalFile, File resizedFile, int width, String format) throws IOException {
- if(format!=null && "gif".equals(format.toLowerCase())){
- resize(originalFile, resizedFile, width, 1);
- return;
- }
- FileInputStream fis = new FileInputStream(originalFile);
- ByteArrayOutputStream byteStream = new ByteArrayOutputStream();
- int readLength = -1;
- int bufferSize = 1024;
- byte bytes[] = new byte[bufferSize];
- while ((readLength = fis.read(bytes, 0, bufferSize)) != -1) {
- byteStream.write(bytes, 0, readLength);
- }
- byte[] in = byteStream.toByteArray();
- fis.close();
- byteStream.close();
- Image inputImage = Toolkit.getDefaultToolkit().createImage( in );
- waitForImage( inputImage );
- int p_w_picpathWidth = inputImage.getWidth( null );
- if ( p_w_picpathWidth < 1 )
- throw new IllegalArgumentException( "p_w_picpath width " + p_w_picpathWidth + " is out of range" );
- int p_w_picpathHeight = inputImage.getHeight( null );
- if ( p_w_picpathHeight < 1 )
- throw new IllegalArgumentException( "p_w_picpath height " + p_w_picpathHeight + " is out of range" );
- // Create output p_w_picpath.
- int height = -1;
- double scaleW = (double) p_w_picpathWidth / (double) width;
- double scaleY = (double) p_w_picpathHeight / (double) height;
- if (scaleW >= 0 && scaleY >=0) {
- if (scaleW > scaleY) {
- height = -1;
- } else {
- width = -1;
- }
- }
- Image outputImage = inputImage.getScaledInstance( width, height, java.awt.Image.SCALE_DEFAULT);
- checkImage( outputImage );
- encode(new FileOutputStream(resizedFile), outputImage, format);
- }
- /** Checks the given p_w_picpath for valid width and height. */
- private static void checkImage( Image p_w_picpath ) {
- waitForImage( p_w_picpath );
- int p_w_picpathWidth = p_w_picpath.getWidth( null );
- if ( p_w_picpathWidth < 1 )
- throw new IllegalArgumentException( "p_w_picpath width " + p_w_picpathWidth + " is out of range" );
- int p_w_picpathHeight = p_w_picpath.getHeight( null );
- if ( p_w_picpathHeight < 1 )
- throw new IllegalArgumentException( "p_w_picpath height " + p_w_picpathHeight + " is out of range" );
- }
- /** Waits for given p_w_picpath to load. Use before querying p_w_picpath height/width/colors. */
- private static void waitForImage( Image p_w_picpath ) {
- try {
- tracker.addImage( p_w_picpath, 0 );
- tracker.waitForID( 0 );
- tracker.removeImage(p_w_picpath, 0);
- } catch( InterruptedException e ) { e.printStackTrace(); }
- }
- /** Encodes the given p_w_picpath at the given quality to the output stream. */
- private static void encode( OutputStream outputStream, Image outputImage, String format )
- throws java.io.IOException {
- int outputWidth = outputImage.getWidth( null );
- if ( outputWidth < 1 )
- throw new IllegalArgumentException( "output p_w_picpath width " + outputWidth + " is out of range" );
- int outputHeight = outputImage.getHeight( null );
- if ( outputHeight < 1 )
- throw new IllegalArgumentException( "output p_w_picpath height " + outputHeight + " is out of range" );
- // Get a buffered p_w_picpath from the p_w_picpath.
- BufferedImage bi = new BufferedImage( outputWidth, outputHeight,
- BufferedImage.TYPE_INT_RGB );
- Graphics2D biContext = bi.createGraphics();
- biContext.drawImage( outputImage, 0, 0, null );
- ImageIO.write(bi, format, outputStream);
- outputStream.flush();
- }
- /**
- * 缩放gif图片
- * @param originalFile 原图片
- * @param resizedFile 缩放后的图片
- * @param newWidth 宽度
- * @param quality 缩放比例 (等比例)
- * @throws IOException
- */
- private static void resize(File originalFile, File resizedFile, int newWidth, float quality) throws IOException {
- if (quality < 0 || quality > 1) {
- throw new IllegalArgumentException("Quality has to be between 0 and 1");
- }
- ImageIcon ii = new ImageIcon(originalFile.getCanonicalPath());
- Image i = ii.getImage();
- Image resizedImage = null;
- int iWidth = i.getWidth(null);
- int iHeight = i.getHeight(null);
- if (iWidth > iHeight) {
- resizedImage = i.getScaledInstance(newWidth, (newWidth * iHeight) / iWidth, Image.SCALE_SMOOTH);
- } else {
- resizedImage = i.getScaledInstance((newWidth * iWidth) / iHeight, newWidth, Image.SCALE_SMOOTH);
- }
- // This code ensures that all the pixels in the p_w_picpath are loaded.
- Image temp = new ImageIcon(resizedImage).getImage();
- // Create the buffered p_w_picpath.
- BufferedImage bufferedImage = new BufferedImage(temp.getWidth(null), temp.getHeight(null),
- BufferedImage.TYPE_INT_RGB);
- // Copy p_w_picpath to buffered p_w_picpath.
- Graphics g = bufferedImage.createGraphics();
- // Clear background and paint the p_w_picpath.
- g.setColor(Color.white);
- g.fillRect(0, 0, temp.getWidth(null), temp.getHeight(null));
- g.drawImage(temp, 0, 0, null);
- g.dispose();
- // Soften.
- float softenFactor = 0.05f;
- float[] softenArray = {0, softenFactor, 0, softenFactor, 1-(softenFactor*4), softenFactor, 0, softenFactor, 0};
- Kernel kernel = new Kernel(3, 3, softenArray);
- ConvolveOp cOp = new ConvolveOp(kernel, ConvolveOp.EDGE_NO_OP, null);
- bufferedImage = cOp.filter(bufferedImage, null);
- // Write the jpeg to a file.
- FileOutputStream out = new FileOutputStream(resizedFile);
- // Encodes p_w_picpath as a JPEG data stream
- JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
- JPEGEncodeParam param = encoder.getDefaultJPEGEncodeParam(bufferedImage);
- param.setQuality(quality, true);
- encoder.setJPEGEncodeParam(param);
- encoder.encode(bufferedImage);
- }
- }
转载于:https://blog.51cto.com/huqianhao/955140