`

图片压缩工具类

    博客分类:
  • J2SE
阅读更多
最近在做一个网上商城的项目

需要图片压缩功能   在网上找了很久都没找到好的  有些是要收费的 ,索性自己写了个图片压缩的工具类 ,但是只能压缩部分图片的格式   图片格式 jpg, png,bmp, gif(非动画)

如果大家有其他的支持其他格式的且免费的    望提供参考  谢谢


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.image.BufferedImage;
import java.awt.image.ConvolveOp;
import java.awt.image.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.imageio.ImageIO;
import javax.swing.ImageIcon;

import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGEncodeParam;
import com.sun.image.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 imageWidth = inputImage.getWidth( null );
        if ( imageWidth < 1 ) 
           throw new IllegalArgumentException( "image width " + imageWidth + " is out of range" );
        int imageHeight = inputImage.getHeight( null );
        if ( imageHeight < 1 ) 
           throw new IllegalArgumentException( "image height " + imageHeight + " is out of range" );
        
        // Create output image.
        int height = -1;
        double scaleW = (double) imageWidth / (double) width;
        double scaleY = (double) imageHeight / (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 image for valid width and height. */
    private static void checkImage( Image image ) {
       waitForImage( image );
       int imageWidth = image.getWidth( null );
       if ( imageWidth < 1 ) 
          throw new IllegalArgumentException( "image width " + imageWidth + " is out of range" );
       int imageHeight = image.getHeight( null );
       if ( imageHeight < 1 ) 
          throw new IllegalArgumentException( "image height " + imageHeight + " is out of range" );
    }

    /** Waits for given image to load. Use before querying image height/width/colors. */
    private static void waitForImage( Image image ) {
       try {
          tracker.addImage( image, 0 );
          tracker.waitForID( 0 );
          tracker.removeImage(image, 0);
       } catch( InterruptedException e ) { e.printStackTrace(); }
    } 

    /** Encodes the given image 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 image width " + outputWidth + " is out of range" );
       int outputHeight = outputImage.getHeight( null );
       if ( outputHeight < 1 ) 
          throw new IllegalArgumentException( "output image height " + outputHeight + " is out of range" );

       // Get a buffered image from the image.
       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 image are loaded.
        Image temp = new ImageIcon(resizedImage).getImage(); 
        // Create the buffered image.
        BufferedImage bufferedImage = new BufferedImage(temp.getWidth(null), temp.getHeight(null),
                                                        BufferedImage.TYPE_INT_RGB); 
        // Copy image to buffered image.
        Graphics g = bufferedImage.createGraphics(); 
        // Clear background and paint the image.
        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 image 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);
    }
}



测试方法

public static void main(String[] args) {
		try {
			ImageSizer.resize(new File("d:\\111.jpg"), new File("d:\\image\\222.jpg"), 200, "jpg");
		} catch (IOException e) {
			e.printStackTrace();
		}

	}
4
3
分享到:
评论
1 楼 Java路 2013-09-09  
nice  好东西!

相关推荐

    Java图片压缩工具类

    Java图片压缩工具类,根据宽度、高度进行压缩图片。如有意见,欢迎指出

    java 写的一个图片压缩工具类

    java 写的一个图片压缩工具类,可以把图片压缩到原来的20%,而且不影响质量

    Android bitmap图片压缩工具类

    "Android bitmap图片压缩工具类"就是针对这一需求设计的一个实用工具,它能够有效地减小图片的大小,同时满足基本的显示要求。 BitmapCompressUtils这个类通常包含了一系列静态方法,用于对Bitmap进行不同类型的...

    android kotlin语言 图片压缩工具类

    kotlin 图片压缩工具类 1.比例缩放图片 2.质量压缩 3.图片按比例大小压缩方法 4.把字节数组保存为一个文件 5. 旋转图片 6.设置缩略图 7.按宽/高缩放图片到指定大小并进行裁剪得到中间部分图片

    Android开发之图片压缩工具类完整实例

    本文实例讲述了Android图片压缩工具类。分享给大家供大家参考,具体如下: 这里共享一个图片压缩工具类: package com.sanweidu.TddPay.util2; import java.io.ByteArrayInputStream; import java.io....

    android图片压缩工具类分享

    本文将介绍一个Android图片压缩工具类的实现,通过这个工具类,开发者可以有效地管理和压缩图片资源,防止因图片过大导致内存溢出或应用运行缓慢。 首先,工具类中的`compressImage(Bitmap image)`方法用于质量压缩...

    java图片压缩工具类

    Java图片压缩工具类是用于处理图像文件的一种实用程序,它可以帮助开发者将图片调整到所需的尺寸,同时保持图像质量。在Java中,我们可以使用内置的`java.awt`和`javax.imageio`包来处理图像。以下是对`ImageProcess...

    Java图片处理工具类,压缩图片

    图片处理工具类,能缩放图片,给图片打水印等。

    PNG图片压缩工具

    PNG图片压缩工具是一种用于减小PNG图像文件大小的软件或在线服务。PNG(Portable Network Graphics)格式因其无损压缩和透明度支持而被广泛应用于网页设计、图形制作和数字艺术领域。然而,PNG文件通常比其他格式如...

    图片压缩小工具

    "图片压缩小工具"就是这样一个专门用于图像处理的应用,它的主要功能是按照原宽高比将图片压缩到用户指定的大小,适合于创建头像或者其他需要限制尺寸的场景。这种工具对于优化网站性能、节省存储空间以及提高数据...

    thumbnailator-0.4.8 图片压缩工具类及调用方法

    在这个压缩包中,你将找到`thumbnailator`库的相关文件,包括类库、示例代码以及可能的文档,帮助你理解和使用这个工具。 `thumbnailator`库的核心是`Thumbnails`类,它提供了多种方法来创建和操作图像的缩略图。...

    Android整理好的图片压缩工具类

    以下是一个简单的图片压缩工具类`ImageCompressUtil`的示例,它包含了通过质量和尺寸压缩图片的方法: ```java public class ImageCompressUtil { // 通过质量压缩方法 public static Bitmap compressByQuality...

    java压缩图片工具类

    java压缩图片工具类

Global site tag (gtag.js) - Google Analytics