图片压缩尺寸与大小

/**

* 按尺寸质量压缩(测试)

* @param is

* @param to

* @param quality

* @throws IOException

*/

public static void compressQuality(InputStream is, File to, float quality, int maxWidth, int maxHeight) throws IOException{

//压缩大小

BufferedImage image = ImageIO.read(is);

if(image==null)return;

Integer width = image.getWidth();

Integer height = image.getHeight();

if(width>maxWidth || height>maxHeight){

ResampleOp resampleOp = new ResampleOp(DimensionConstrain.createMaxDimension(maxWidth, maxHeight));

image = resampleOp.filter(image, null);

}

// 得到指定Format图片的writer 

Iterator<ImageWriter> iter =  ImageIO.getImageWritersByFormatName("jpeg");

ImageWriter imageWriter = iter.next();

 

// 得到指定writer的输出参数设置(ImageWriteParam )  

        ImageWriteParam iwp = imageWriter.getDefaultWriteParam();  

        iwp.setCompressionMode(ImageWriteParam.MODE_EXPLICIT); // 设置可否压缩  

        iwp.setCompressionQuality(quality); // 设置压缩质量参数  

        iwp.setProgressiveMode(ImageWriteParam.MODE_DISABLED);

        

        ColorModel colorModel = ColorModel.getRGBdefault();  

        // 指定压缩时使用的色彩模式  

        iwp.setDestinationType(new javax.imageio.ImageTypeSpecifier(colorModel,  

                colorModel.createCompatibleSampleModel(16, 16)));

        

        // 开始打包图片,写入byte[]  

        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); // 取得内存输出流  

        IIOImage iIamge = new IIOImage(image, null, null); 

        

        // 此处因为ImageWriter中用来接收write信息的output要求必须是ImageOutput  

        // 通过ImageIo中的静态方法,得到byteArrayOutputStream的ImageOutput  

        imageWriter.setOutput(ImageIO  

                .createImageOutputStream(byteArrayOutputStream));  

        imageWriter.write(null, iIamge, iwp); 

        

        InputStream sbs = new ByteArrayInputStream(byteArrayOutputStream.toByteArray());

        ImageIO.write(ImageIO.read(sbs), "png", to);

        

}

你可能感兴趣的:(java,图片)