1

这里展示一下如何对图片进行压缩和resize。

压缩

public static boolean compress(String src,String to, float quality) {
        boolean rs = true;

        // Build param
        JPEGEncodeParam param = null;

        // Build encoder
        File destination = new File(to);
        FileOutputStream os = null;
        try {
            BufferedImage image = ImageIO.read(new File(src));
            param = JPEGCodec.getDefaultJPEGEncodeParam(image);
            param.setQuality(quality, false);

            os = FileUtils.openOutputStream(destination);
            JPEGImageEncoder encoder;
            if (param != null) {
                encoder = JPEGCodec.createJPEGEncoder(os, param);
            } else {
                return false;
            }
            encoder.encode(image);
        } catch(Exception e){
            e.printStackTrace();
            rs = false;
        }finally {
            IOUtils.closeQuietly(os);
        }
        return rs;
    }

resize

public static boolean resize(String src,String to,int newWidth,int newHeight) {
        try {
            File srcFile = new File(src);
            File toFile = new File(to);
            BufferedImage img = ImageIO.read(srcFile);
            int w = img.getWidth();
            int h = img.getHeight();
            BufferedImage dimg  = new BufferedImage(newWidth, newHeight, img.getType());
            Graphics2D g = dimg.createGraphics();
            g.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
            g.drawImage(img, 0, 0, newWidth, newHeight, 0, 0, w, h, null);
            g.dispose();
            ImageIO.write(dimg, "jpg", toFile);
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }

codecraft
11.9k 声望2k 粉丝

当一个代码的工匠回首往事时,不因虚度年华而悔恨,也不因碌碌无为而羞愧,这样,当他老的时候,可以很自豪告诉世人,我曾经将代码注入生命去打造互联网的浪潮之巅,那是个很疯狂的时代,我在一波波的浪潮上留下...