---
title: "图片等比压缩"
author: "lzstone"
date: "2011-04-15T14:23:22Z"
tags: []
categories: ["编程语言"]
slug: "untitled"
draft: false
lastmod: "2011-04-15T14:23:22Z"
id: 1004149
url: "https://lzstone.iteye.com/blog/1004149"
---

好久没有写博客了，最近遇到一个有意思的问题就是需要动态的将用户上传的图片进行缩小

下面是实现方式，希望对有此需求的朋友有所帮助

 

import com.sun.image.codec.jpeg.JPEGCodec;  
import com.sun.image.codec.jpeg.JPEGImageEncoder;

public class ZipImage {  
    public static void transImage(String sourcePath, String descPath, int width, int height){  
        File \_file = new File(sourcePath); //读入文件路径        
        Image src = null; //构造Image对象  
        try  
        {            
            src = javax.imageio.ImageIO.read(\_file);

            /\**  
            int wideth=src.getWidth(null); //得到源图宽  
            int height=src.getHeight(null); //得到源图长

            \*\*/  
            BufferedImage tag = new BufferedImage(width,height,BufferedImage.TYPE\_INT\_RGB);  
            tag.getGraphics().drawImage(src,0,0,width,height,null); //绘制缩小后的图  
            FileOutputStream out=new FileOutputStream(descPath); //输出到文件流  
            JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);  
            encoder.encode(tag); //近JPEG编码  
            out.close();  
        }  
        catch (IOException e) {  
            e.printStackTrace();  
        }  
    }     
     
}