日期:2014-05-19  浏览次数:21023 次

java 压缩图片 图片长度和宽度固定 怎么调整图片的分辨率
这是压缩图片的方法:
//压缩图片
private static BufferedImage resize(BufferedImage source, int targetW,   
            int targetH) {    
        // targetW,targetH分别表示目标长和宽    
        int type = source.getType();    
        BufferedImage target = null;    
        double sx = (double) targetW / source.getWidth();    
        double sy = (double) targetH / source.getHeight();    
        // 这里想实现在targetW,targetH范围内实现等比缩放。如果不需要等比缩放    
        // 则将下面的if else语句注释即可    
        if (sx < sy) {  
            sy = sx;    
            targetH = (int) (sx * source.getHeight());              
        } else {    
            sx = sy;    
            targetW = (int) (sy * source.getWidth()); 
        }    
        if (type == BufferedImage.TYPE_CUSTOM) { // handmade    
            ColorModel cm = source.getColorModel();    
            WritableRaster raster = cm.createCompatibleWritableRaster(targetW,   
                    targetH);    
            boolean alphaPremultiplied = cm.isAlphaPremultiplied();    
            target = new BufferedImage(cm, raster, alphaPremultiplied, null);   
        } else   
            target = new BufferedImage(targetW, targetH, type);    
        Graphics2D g = target.createGraphics();    
        // smoother than exlax:    
        g.setRenderingHint(RenderingHints.KEY_INTERPOLATION,    
                RenderingHints.VALUE_INTERPOLATION_BICUBIC);    
      &n