圖片處理工具(JAVA)

圖片處理工具(JAVA)


package com.michael.utils;

import lombok.extern.slf4j.Slf4j;

import javax.imageio.stream.FileImageInputStream;
import javax.imageio.stream.FileImageOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;

/**
 * 圖片處理
 * <p>
 * Created by michael on 2015-12-21
 */
@Slf4j
public class ImageUtils {

    /**
     * 寬
     */
    private static final Integer WIDTH = 300;

    /**
     * 高
     */
    private static final Integer HEIGHT = 300;

    /**
     * 圖片質量
     */
    private static final Float QUALITY = 0.9f;

    /**
     * 壓縮圖片
     *
     * @param sourceFilePath 源文件路徑
     * @param newFilepath    新文件路徑(即:壓縮之後的文件路徑)
     * @param width          寬
     * @param height         高
     * @param quality        圖片質量
     * @return
     */
    public static String compression(String sourceFilePath, String newFilepath, int width, int height, float quality) {
        try {
            if (Strings.isEmpty(sourceFilePath))
                return null;

            File file = new File(sourceFilePath);
            if (!file.exists()) {
                log.warn("源文件不存在,請檢查");
                throw new Exception("源文件不存在,請檢查");
            }

            if (Strings.isNotEmpty(newFilepath)) {
                File f = new File(newFilepath);
                if (!f.exists())
                    f.mkdirs();
            }

            // 對服務器上的臨時文件進行處理
            Image srcFile = ImageIO.read(new File(sourceFilePath));

            // 設定高寬
            BufferedImage bImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
            bImage.getGraphics().drawImage(srcFile, 0, 0, width, height, null);

            // 壓縮後的文件名
            String newFileAbsolutePath = newFilepath + "//" + Strings.uuid() + "_" + width + "×" + height + sourceFilePath.substring(sourceFilePath.lastIndexOf("."));
            log.info("壓縮圖片路徑:{}", newFileAbsolutePath);

            // 壓縮之後存放位置
            FileOutputStream out = new FileOutputStream(newFileAbsolutePath);
            JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
            JPEGEncodeParam jep = JPEGCodec.getDefaultJPEGEncodeParam(bImage);

            // 壓縮質量
            jep.setQuality(quality, true);
            encoder.encode(bImage, jep);
            out.close();

            return newFileAbsolutePath;

        } catch (FileNotFoundException e) {
            log.error("圖片壓縮過程中出錯:{}", e.getMessage());
            e.printStackTrace();
        } catch (IOException e) {
            log.error("圖片壓縮過程中出錯:{}", e.getMessage());
            e.printStackTrace();
        } catch (Exception e) {
            log.error("圖片壓縮過程中出錯:{}", e.getMessage());
            e.printStackTrace();
        }
        return "";
    }

    /**
     * 壓縮圖片
     *
     * @param sourceFilePath 源文件路徑
     * @param newFilepath    新文件路徑(即:壓縮之後的文件路徑)
     * @return
     */
    public static String compression(String sourceFilePath, String newFilepath) {
        return compression(sourceFilePath, newFilepath, WIDTH, HEIGHT, QUALITY);
    }

    /**
     * 圖片轉換爲byte數組
     *
     * @param path  圖片絕對路徑
     * @return
     */
    public static byte[] image2byte(String path) {
        byte[] data = null;
        FileImageInputStream input = null;
        try {
            input = new FileImageInputStream(new File(path));
            ByteArrayOutputStream output = new ByteArrayOutputStream();
            byte[] buf = new byte[1024];
            int numBytesRead = 0;
            while ((numBytesRead = input.read(buf)) != -1) {
                output.write(buf, 0, numBytesRead);
            }
            data = output.toByteArray();
            output.close();
            input.close();
        } catch (FileNotFoundException ex1) {
            ex1.printStackTrace();
        } catch (IOException ex1) {
            ex1.printStackTrace();
        }
        return data;
    }

    /**
     * byte數組轉換爲圖片
     *
     * @param data byte數組
     * @param path 輸出路徑, 如:F://Wallpaper//temp//XXXXXXXXX.jpg
     */
    public static void byte2image(byte[] data, String path) {
        if (data.length < 3 || path.equals("")) return;
        try {
            FileImageOutputStream imageOutput = new FileImageOutputStream(new File(path));
            imageOutput.write(data, 0, data.length);
            imageOutput.close();
            log.info("Make Picture success, Please find image in {}", path);

        } catch (Exception ex) {
            log.error("Exception: {}", ex);
            ex.printStackTrace();
        }
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章