1. 程式人生 > >用到了base64轉圖片文件的函數,記錄一下

用到了base64轉圖片文件的函數,記錄一下

base64 圖片

import java.io.*;
import sun.misc.*;

    //對圖片文件進行Base64編碼
    public String getImagebase64(String imgFileName) {
        byte[] data = null;
        try {
            InputStream in = new FileInputStream(imgFileName);
            data = new byte[in.available()];
            in.read(data);
            in.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        
        BASE64Encoder encoder = new BASE64Encoder();
        return encoder.encode(data);
    }

    //Base64解碼並保存圖片文件
    public void saveImage(String base64, String imgFileName) {
        BASE64Decoder decoder = new BASE64Decoder();
        try {
            byte[] bytes = decoder.decodeBuffer(base64);
            for (int i = 0; i < bytes.length; ++i) {
                if (bytes[i] < 0) {
                    bytes[i] += 256;
                }
            }
            OutputStream out = new FileOutputStream(imgFileName);
            out.write(bytes);
            out.flush();
            out.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

具體來說是因為這個原因:前端使用某個richEditor控件,當粘貼圖片時會自動以base64數據的格式存放,考慮到直接存進數據庫一來會有性能問題,二來會有字段長度問題,所以先把這些base64數據提取出來,保存成文件,再用文件路徑替換img src=""中的內容,即可達到目的。

本文出自 “空空如也” 博客,謝絕轉載!

用到了base64轉圖片文件的函數,記錄一下