java代码实现图片处理功能。对图片质量进行压缩。

java图片处理有点头疼,找了很多资料。在这里进行一个汇总,记录下个人的体验,也希望对大家有所帮助。

需求:浏览的图片需要在1M一下。

1、真正对图片的质量进行压缩的(不是通过修改图片的高,宽进行缩小图片。就单单缩小图片质量)

  优点:不修改图片大小,简便。

  缺点:对jpg格式能处理很好,对于gif,png其他格式不适合。

compressPic(图片路径,处理格式);
        /**
         * 
         * 修改图片大小
         * <p>描述</p>
         * @date 2014-7-10 下午4:27:51
         * @version 
         * @param srcFilePath
         * @param fileExtName
         * @return
         * @throws IOException
         */
        public static boolean compressPic(String srcFilePath,String fileExtName) throws IOException {
            File file = null;
            BufferedImage src = null;
            FileOutputStream out = null;
            ImageWriter imgWrier;
            ImageWriteParam imgWriteParams;


            long start1 = System.currentTimeMillis();
            // 指定写图片的方式为 jpg
            imgWrier = ImageIO.getImageWritersByFormatName(fileExtName).next();
            imgWriteParams = imgWrier.getDefaultWriteParam();
//            imgWriteParams = new javax.imageio.plugins.jpeg.JPEGImageWriteParam(
//                    null);
//            imgWriteParams = new javax.imageio.plugins.jpeg.JPEGImageWriteParam(
//                    null);
            
            
            imgWriteParams.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
            // 这里指定压缩的程度,参数qality是取值0~1范围内,
            imgWriteParams.setCompressionQuality((float) 0.2);
            //imgWriteParams.setProgressiveMode(ImageWriteParam.MODE_DISABLED);//
            ColorModel colorModel =ImageIO.read(new File(srcFilePath)).getColorModel();// ColorModel.getRGBdefault();
            // 指定压缩时使用的色彩模式

            imgWriteParams.setDestinationType(new javax.imageio.ImageTypeSpecifier(
                    colorModel, colorModel.createCompatibleSampleModel(16, 16)));

            long end1 = System.currentTimeMillis();
            System.out.println("11111消耗时间:"+((double)end1-(double)start1)/1000+"秒");
            try {
                if (isBlank(srcFilePath)) {
                    return false;
                } else {
                    file = new File(srcFilePath);
                    src = ImageIO.read(file);
                    out = new FileOutputStream(srcFilePath);
                    
                    System.out.println("22222");
                    imgWrier.reset();
                   
                    // 必须先指定 out值,才能调用write方法, ImageOutputStream可以通过任何
                    // OutputStream构造
                    imgWrier.setOutput(ImageIO.createImageOutputStream(out));
                    System.out.println("3333333");
                    // 调用write方法,就可以向输入流写图片

                    long start4 = System.currentTimeMillis();
                    imgWrier.write(null, new IIOImage(src, null, null),
                            imgWriteParams);
                    long end4 = System.currentTimeMillis();

                    System.out.println("4444消耗时间:"+((double)end4-(double)start4)/1000+"秒");

                    src.flush();
                    out.flush();
                    out.close();
                    imgWrier.dispose();
                }
            } catch (Exception e) {
                e.printStackTrace();
                return false;
            }
            return true;
        }


/**
         * 
         * 修改单独图片大小
         * <p>描述</p>
         * @date 2014-7-10 下午4:26:30
         * @version 
         * @param filePath
         * @param createType
         * @throws Exception
         */
        public static void changeNoneImgSize(String filePath,String createType) throws Exception
        {
            File tempFile = new File(filePath);
            if(tempFile.length()>ImagesUtils.IMAGEMAXSIZE){
                
                long start = System.currentTimeMillis();


                compressPic(filePath,createType);
                long end = System.currentTimeMillis();
                

                System.out.println(filePath+"消耗时间:"+((double)end-(double)start)/1000+"秒");
            }
            
        }


/**
         * 
         * 修改多个图片大小
         * <p>描述</p>
         * @date 2014-7-10 下午4:26:52
         * @version 
         * @param file
         * @throws Exception
         */
         public static void changeManyImgSize(File file) throws Exception
         {
             try {
                    // 判断文件是否是文件,如果是文件,获取路径,并计数
                    if (file.isFile()) {
                        String fileExtName = file.getName().substring(  
                                (file.getName().lastIndexOf(".") + 1), file.getName().length());  
                        if(ImagesUtils.isImageFile(fileExtName))
                            changeNoneImgSize(file.getAbsolutePath(), fileExtName);
                            //ImagesUtils.changeImgSize(file.getAbsolutePath(), ImagesUtils.CREATENEWIMAGETYPE_6);
                    } else {
                        // 如果是文件夹,声明一个数组放文件夹和他的子文件
                        File[] f = file.listFiles();
                        // 遍历文件件下的文件,并获取路径
                        for (File file2 : f) {
                            changeManyImgSize(file2);
                        }
                    }
                } catch (RuntimeException e) {
                    e.printStackTrace();
                }
         }

2,这种需要用到一个java-image-scaling-0.8.5.jar包。这种需要设定宽高(我是按照原来比例走的。宽是按照两个A4的宽度走),jar我这里提供出来:http://pan.baidu.com/s/1c0pekVm

优点:简单,格式支持还行。我测试了gif,png都可以用、

缺点:宽高需要设定。

  

public static boolean compressPic(String srcFilePath,String fileExtName) throws IOException {
        
        
        try {
            BufferedImage sourceImage = ImageIO.read(new File(srcFilePath));
            int newwidth = 1700;
            double newheight = ((double) sourceImage.getHeight() / (double) sourceImage.getWidth()) * 1700;
            ResampleOp resizeOp = new ResampleOp(newwidth, (int) newheight);
            resizeOp.setFilter(ResampleFilters.getTriangleFilter());
            BufferedImage resizedImage = resizeOp.filter(sourceImage, null);
            ImageIO.write(resizedImage, "jpg", new File(srcFilePath));
        } catch (Exception e) {
            log.error("compressPic error", e);
            return false;
        }
      return true;
    }

有点忙,先写这了..................后续还有,不只这点资料。