天天看點

Java圖檔處理工具包

根據輸入流轉base64

public static String imageToBase64ByInpusSteam(InputStream is) {
        ByteArrayOutputStream data = new ByteArrayOutputStream();
        try {
            // 建立URL
            byte[] by = new byte[1024];
            // 将内容讀取記憶體中
            int len = -1;
            while ((len = is.read(by)) != -1) {
                data.write(by, 0, len);
            }
            // 關閉流
            is.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        // 對位元組數組Base64編碼
        BASE64Encoder encoder = new BASE64Encoder();
        return encoder.encode(data.toByteArray()).replaceAll("\r|\n", "");
    }
           

根據base64轉換為位元組數組

public static byte[] base64ToImage(String imgStr) {

        if (StringUtils.isEmpty(imgStr)){
            return null;
        }

        BASE64Decoder decoder = new BASE64Decoder();
        try {
            // Base64解碼
            byte[] b = decoder.decodeBuffer(imgStr);
            for (int i = 0; i < b.length; ++i) {
                if (b[i] < 0) {// 調整異常資料
                    b[i] += 256;
                }
            }

            return b;
        } catch (Exception e) {
            return null;
        }

    }
           

根據url轉換為位元組數組

public static byte[] getImageFromNetByUrl(String strUrl) {
        if (StringUtils.isEmpty(strUrl)|| !isURL(strUrl)){
            return null;
        }
        try {
            URL url = new URL(strUrl);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("GET");
            conn.setConnectTimeout(2 * 1000);
            InputStream inStream = conn.getInputStream();
            byte[] btImg = readInputStream(inStream);
            return btImg;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
           

根據輸入流轉位元組數組

public static byte[] readInputStream(InputStream inStream) throws Exception {
        ByteArrayOutputStream outStream = new ByteArrayOutputStream();
        byte[] buffer = new byte[10240];
        int len = 0;
        while ((len = inStream.read(buffer)) != -1) {
            outStream.write(buffer, 0, len);
        }
        inStream.close();
        return outStream.toByteArray();
    }
           

判斷該字元串是否為url

public static boolean isURL(String str) {
        str = str.toLowerCase();
        String regex = "^((https|http|ftp|rtsp|mms)?://)"
                + "?(([0-9a-z_!~*'().&=+$%-]+: )?[0-9a-z_!~*'().&=+$%-][email protected])?"
                + "(([0-9]{1,3}\\.){3}[0-9]{1,3}"
                + "|"
                + "([0-9a-z_!~*'()-]+\\.)*"
                + "([0-9a-z][0-9a-z-]{0,61})?[0-9a-z]\\."
                + "[a-z]{2,6})"
                + "(:[0-9]{1,5})?"
                + "((/?)|"
                + "(/[0-9a-z_!~*'().;?:@&=+$,%#-]+)+/?)$";
        return str.matches(regex);
    }
           

根據url轉base64

public static String imageToBase64ByOnline(String imgURL) {
        ByteArrayOutputStream data = new ByteArrayOutputStream();
        try {
            // 建立URL
            URL url = new URL(imgURL);
            byte[] by = new byte[1024];
            // 建立連結
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("GET");
            conn.setConnectTimeout(5000);
            InputStream is = conn.getInputStream();
            // 将内容讀取記憶體中
            int len = -1;
            while ((len = is.read(by)) != -1) {
                data.write(by, 0, len);
            }
            // 關閉流
            is.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        // 對位元組數組Base64編碼
        BASE64Encoder encoder = new BASE64Encoder();
        return encoder.encode(data.toByteArray()).replaceAll("\r|\n", "");
    }

           

根據路徑轉base64

public static String ImageToBase64ByLocal(String imgFile) {// 将圖檔檔案轉化為位元組數組字元串,并對其進行Base64編碼處理

        InputStream in = null;
        byte[] data = null;
        // 讀取圖檔位元組數組
        try {
            in = new FileInputStream(imgFile);
            data = new byte[in.available()];
            in.read(data);
            in.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        // 對位元組數組Base64編碼
        BASE64Encoder encoder = new BASE64Encoder();

        return Base64.getEncoder().encodeToString(data).replaceAll("\r|\n", "");
    }
           

壓縮檔案

<dependency>
            <groupId>net.coobird</groupId>
            <artifactId>thumbnailator</artifactId>
            <version>0.4.11</version>
</dependency>
           
public void compressPic(String filePath,HttpServletResponse response){
        try {
            Thumbnails.of(filePath).scale(1f).outputQuality(0.5f).toOutputStream(response.getOutputStream());
        } catch (IOException e) {
            e.printStackTrace();
        }
}