java圖片轉base64


package org.jeecg.common.util;

import org.apache.commons.codec.binary.Base64;
import sun.misc.BASE64Decoder;

import java.io.*;

public class ImgBase64 {
    /**
     * 將圖片轉換成Base64編碼
     * @param imgFile 待處理圖片
     * @return
     */
    public static String getImgStr(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();
        }
        return Base64.encodeBase64String(data);
    }

    /**
     * 對字節數組字符串進行Base64解碼並生成圖片
     * @param imgStr 圖片數據
     * @param imgFilePath 保存圖片全路徑地址
     * @return
     */
    public static boolean generateImage(String imgStr, String imgFilePath) {
        //
        if (imgStr == null) // 圖像數據為空
            return false;
        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;
                }
            }
            // 生成jpg圖片
            OutputStream out = new FileOutputStream(imgFilePath);
            out.write(b);
            out.flush();
            out.close();
            return true;
        } catch (Exception e) {
            return false;
        }
    }
}

  調用:

        String url= "D:\\1.jpg";// 待處理的圖片
        String imgbese = getImgStr(url);
        String img_path="data:image/jpeg;base64,"+imgbese ;
       
        String url= "D:\\1.jpg";// 新生成的圖片
        generateImage(imgbese, url);
    

  jar包:

<dependency>
<groupId>commons-codec</groupId>
<artifactId>commons-codec</artifactId>
<version>1.13</version>
</dependency>


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM