1. 程式人生 > >壓縮圖片工具類ZipImageUtil

壓縮圖片工具類ZipImageUtil

四個常量配置引數可以按需求做相應調整。

public class ZipImageUtil {

    private final static int FILE_SIZE_LIMIT = 100 * 1024;
    private final static int STREAM_SIZE_LIMIT = 100 * 1024;
    private final static double POW_SIZE = 0.5D;
    private final static String FILE_NAME_SUFFIX = "jpg";

    public static File zipByScale(File srcFile) throws Exception {
        long oldSize = srcFile.length();
        double scale = 1.0d;
        if (oldSize >= FILE_SIZE_LIMIT) {
            scale = ((double) FILE_SIZE_LIMIT) / oldSize;
        } else {
            return null;
        }
        scale = Math.pow(scale, POW_SIZE);
        Image oldF = ImageIO.read(srcFile);
        int oldWidth = oldF.getWidth(null);
        int oldHeight = oldF.getHeight(null);
        int width = (int) (oldWidth * scale);
        int height = (int) (oldHeight * scale);
        BufferedImage buffImg = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        Graphics2D graphics = buffImg.createGraphics();
        graphics.setBackground(new Color(255, 255, 255));
        graphics.setColor(new Color(255, 255, 255));
        graphics.fillRect(0, 0, width, height);
        graphics.drawImage(oldF.getScaledInstance(width, height, Image.SCALE_SMOOTH), 0, 0, null);
        ImageIO.write(buffImg, FILE_NAME_SUFFIX, srcFile);
        return srcFile;
    }

    public static InputStream zipByScale(InputStream inputStream) throws Exception {
        long oldSize = inputStream.available();
        double scale = 1.0d;
        if (oldSize >= STREAM_SIZE_LIMIT) {
            scale = ((double) STREAM_SIZE_LIMIT) / oldSize;
        } else {
            return inputStream;
        }
        scale = Math.pow(scale, POW_SIZE);
        Image oldF = ImageIO.read(inputStream);
        int oldWidth = oldF.getWidth(null);
        int oldHeight = oldF.getHeight(null);
        int width = (int) (oldWidth * scale);
        int height = (int) (oldHeight * scale);
        BufferedImage buffImg = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        Graphics2D graphics = buffImg.createGraphics();
        graphics.setBackground(new Color(255, 255, 255));
        graphics.setColor(new Color(255, 255, 255));
        graphics.fillRect(0, 0, width, height);
        graphics.drawImage(oldF.getScaledInstance(width, height, Image.SCALE_SMOOTH), 0, 0, null);
        ByteArrayOutputStream swapStream = new ByteArrayOutputStream();
        int ch = 0;
        while ((ch = inputStream.read()) != -1) {
            swapStream.write(ch);
        }
        ImageIO.write(buffImg, FILE_NAME_SUFFIX, swapStream);
        ByteArrayInputStream input = new ByteArrayInputStream(swapStream.toByteArray());
        return input;

    }
}