如何使用Java實現圖片壓縮功能

import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGImageEncoder;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.*;

public class ImageZipUtil {

    /**
     * 採用指定寬度、高度或壓縮比例 的方式對圖片進行壓縮
     *
     * @param: [imgSrc, imgOut, width, height, rate] // rate:爲空時按指定大小壓縮,不爲空時按原尺寸壓縮
     * @return: void
     **/
    public static boolean reduceImg(String imgSrc, String imgOut, int width, int height, Float rate) {
        try {
            File srcfile = new File(imgSrc);
            // 檢查文件是否存在
            if (!srcfile.exists()) {
                return false;
            }
            // 如果rate不爲空說明是按比例壓縮
            if (rate != null && rate > 0) {
                // 獲取文件高度和寬度
                int[] results = getImgWidth(srcfile);
                if (results == null || results[0] == 0 || results[1] == 0) {
                    return false;
                } else {
                    width = (int) (results[0] * rate);
                    height = (int) (results[1] * rate);
                }
            }
            // 開始讀取文件並進行壓縮
            Image src = ImageIO.read(srcfile);
            BufferedImage tag = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
            tag.getGraphics().drawImage(src.getScaledInstance(width, height, Image.SCALE_SMOOTH), 0, 0, null);
            FileOutputStream out = new FileOutputStream(imgOut);
            JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
            encoder.encode(tag);
            out.close();
            return true;
        } catch (IOException ex) {
            ex.printStackTrace();
            return false;
        }
    }

    /**
     * 獲取圖片的長寬
     *
     * @param: [file]
     * @return: int[]
     **/
    private static int[] getImgWidth(File file) {
        int[] result = {0, 0};
        try {
            FileInputStream is = new FileInputStream(file);
            BufferedImage src = ImageIO.read(is);
            // 得到源圖寬
            result[0] = src.getWidth(null);
            // 得到源圖高
            result[1] = src.getHeight(null);
            is.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章