图片压缩

/**  
 * Copyright 2008 pantosoft. All rights reserved.  
 */  
import java.awt.Image;   
import java.awt.image.BufferedImage;   
import java.io.BufferedReader;   
import java.io.File;   
import java.io.FileNotFoundException;   
import java.io.FileOutputStream;   
import java.io.IOException;   
import java.io.InputStreamReader;   
import java.io.OutputStream;   
  
import com.sun.image.codec.jpeg.JPEGCodec;   
import com.sun.image.codec.jpeg.JPEGImageEncoder;   
  
/**  
 * 针对特定文件夹下的所有子目录图片文件缩略图  
 *      要求: 1.安装好jdk,并且配置好运行环境;  
 *              2.文件小于1mb;  
 *              3.文件后缀为:“jpg,jpeg,gif,bmp”中的一种或几种;  
 * 使用方法:1.widows平台下,安装JDK后,直接运行ImageResizer.bat即可。  
 * 注意:支持递归生成策略。  
 *   
 * @author Cheng 2008-9-22 上午11:26:46  
 * @version 1.0.0  
 */  
public class ImageResizer {   
    private static final String PIC_TEMPORARY   = "_temporary.db";   
    private static final String LOG_FILE_NAME   = "operate.log";   
    private static int          successed       = 0;   
    private static int          allFiles        = 0;   
    private String              dir             = null;   
    private StringBuilder       failedFiles     = new StringBuilder();   
    private StringBuilder       infomation      = new StringBuilder();   
  
    /**  
     * 构造函数,初始化目标文件夹  
     * @param dir  
     */  
    public ImageResizer(String dir) {   
        this.dir = dir;   
    }   
  
    public void operate(String _path) {   
        if (_path == null)   
            throw new NullPointerException("您还没有初始化需要操作的文件路径。");   
        File file = new File(_path);   
        if (!file.exists()) {   
            return;   
        }   
        File[] files = file.listFiles();   
        if (files.length >= 10000) {   
            write(_path + "目录下文件大于10000个,请分批处理!");   
            return;   
        } else {   
            for (int i = 0; i < files.length; i++) {   
                allFiles++;   
                if (files[i].isDirectory()) {   
                    write("处理目录:" + files[i].getAbsolutePath());   
                    this.operate(files[i].getAbsolutePath());   
                } else {   
                    write("\t处理文件:" + files[i].getName());   
                    if (files[i].length() > 1000000) {   
                        write("\t超大:" + files[i].getAbsoluteFile() + "["  
                                + files[i].length() + "]字节。");   
                        failedFiles.append("\t超大:" + files[i].getAbsoluteFile()   
                                + "[" + files[i].length() / 1000 + "]字节。\n");   
                        continue;   
                    }   
                    if (files[i].getName().indexOf(".") != -1) {   
                        //已经是缩略图文件了   
                        if (files[i].getName().indexOf(PIC_TEMPORARY) != -1)   
                            continue;   
                        String ext = files[i].getName().substring(   
                                files[i].getName().lastIndexOf("."),   
                                files[i].getName().length()).toLowerCase();   
                        if (ext.equals(".jpg") || ext.equals(".gif")   
                                || ext.equals(".bmp")) {   
                            write("\t压缩:" + files[i].getName() + "...");   
                            resize(files[i]);   
                            write("\t完成:" + files[i].getName() + "");   
                        }   
                    } else {   
                        write("文件类型未知!");   
                    }   
                }   
            }   
        }   
    }   
  
    /**  
     * 输出,方便拓展成log4j,或者其它形式。  
     * @param str  
     */  
    public void write(String str) {   
        infomation.append("\n").append(str);   
    }   
  
    private void flush() {   
        if (this.dir == null || this.dir.equals(""))   
            throw new NullPointerException(   
                    "destinate folder is null or its value is empty.");   
        File file = null;   
        if (file == null || file.exists()) {   
            file = new File(this.dir + "/" + LOG_FILE_NAME);   
        }   
        try {   
            OutputStream stream = new FileOutputStream(file, false);   
            stream.write((this.infomation.toString()).getBytes());   
            if (this.failedFiles.toString().length() != 0) {   
                stream.write("\n\n\n--失败文件列表--\n".getBytes());   
                stream.write((this.failedFiles.toString()).getBytes());   
                stream.write("\n--------------".getBytes());   
            }   
            stream.flush();   
            stream.close();   
        } catch (FileNotFoundException ex) {   
            // TODO Auto-generated catch block   
            ex.printStackTrace();   
        } catch (IOException ex) {   
            // TODO Auto-generated catch block   
            ex.printStackTrace();   
        }   
    }   
  
    public void resize(File _file) {   
        if (_file == null || _file.length() == 0) {   
            throw new NullPointerException("目标文件错误!");   
        }   
        ImageUtils imageUtils = null;   
        try {   
            imageUtils = new ImageUtils(_file);   
            imageUtils.resize(160, 140);   
  
        } catch (IOException ex) {   
            ex.printStackTrace();   
        }   
    }   
  
    /**  
     * 获取出如流,并转换成String  
     * @return  
     */  
    private static String inputString() {   
        BufferedReader bufferedreader = new BufferedReader(   
                new InputStreamReader(System.in));   
        String s = null;   
        try {   
            s = bufferedreader.readLine();   
        } catch (IOException ioexception) {   
            ioexception.printStackTrace();   
        }   
        return s;   
    }   
  
    /**  
     *   
     * @author Cheng 2008-9-27 上午10:32:18  
     * @version 1.0.0  
     */  
    private static class ImageUtils {   
        private Image   srcImage    = null;   
        /**  
         * 源图片文件  
         */  
        private File    srcFile     = null;   
        /**  
         * 目标文件  
         */  
        private File    destFile    = null;   
  
        private String  fileSuffix  = null;   
  
        /**  
         * 构造函数  
         * @param fileName  
         * @throws IOException  
         */  
        public ImageUtils(String fileName) throws IOException {   
            this(new File(fileName));   
        }   
  
        /**  
         *   
         * @param fileName  
         * @throws IOException  
         */  
        public ImageUtils(File fileName) throws IOException {   
            File _file = fileName;   
            _file.setReadOnly();   
            this.srcFile = _file;   
            this.fileSuffix = _file.getName().substring(   
                    (_file.getName().indexOf(".") + 1),   
                    (_file.getName().length()));   
            this.destFile = new File(this.srcFile.getPath().substring(0,   
                    (this.srcFile.getPath().lastIndexOf(".")))   
                    + PIC_TEMPORARY + "." + this.fileSuffix);   
            srcImage = javax.imageio.ImageIO.read(_file);   
        }   
  
        /**  
         * 强制压缩/放大图片到固定的大小  
         * @param w int 新宽度  
         * @param h int 新高度  
         * @throws IOException  
         */  
        public void resize(int w, int h) throws IOException {   
            //构建图片对象   
            BufferedImage _image = new BufferedImage(w, h,   
                    BufferedImage.TYPE_INT_RGB);   
            //绘制缩小后的图   
            _image.getGraphics().drawImage(srcImage, 0, 0, w, h, null);   
            //输出到文件流   
            FileOutputStream out = new FileOutputStream(destFile);   
            JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);   
            encoder.encode(_image);   
            out.flush();   
            out.close();   
            successed++;   
        }   
    }   
  
    /**  
     * 测试Main  
     * @param args  
     */  
    public static void main(String[] args) {   
        System.out.print("请输入目标文件夹:");   
        String s = inputString();   
        long currentTime = System.currentTimeMillis();   
        ImageResizer resizer = new ImageResizer(s);   
        resizer.operate(s);   
        long finishTime = System.currentTimeMillis();   
        long waste = finishTime - currentTime;   
        resizer.write(s + "下共有" + allFiles + "个文件\n" + "\t成功:" + successed   
                + "\n\t失败:" + (allFiles - successed));   
        resizer.write("耗时:" + waste / 1000 + "s");   
        resizer.flush();   
        System.out.println("处理完成,请看目标文件夹下日志文件。");   
    }   
}  

你可能感兴趣的:(jdk,log4j,ext,sun)