Java將圖片轉出base64,將base64轉出圖片

如何使用Java將圖片轉出base64,將base64轉出圖片

如下需求
在這裏插入圖片描述
圖片轉成base64

//圖片轉base64
	public static String getImageStr(String imgFile) {
		InputStream inputStream = null;
		byte[] data = null;
		try {
			inputStream = new FileInputStream(imgFile);
			data = new byte[inputStream.available()];
			inputStream.read(data);
			inputStream.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
		BASE64Encoder encoder = new BASE64Encoder();
		return encoder.encode(data);
	}

base64轉成圖片

//base64 轉成圖片
    public static boolean generateImage(String imgStr, String imgFilePath) {// 對字節數組字符串進行Base64解碼並生成圖片
        if (imgStr == null) // 圖像數據爲空
            return false;
        BASE64Decoder decoder = new BASE64Decoder();
        try {
            // Base64解碼
            byte[] bytes = decoder.decodeBuffer(imgStr);
            for (int i = 0; i < bytes.length; ++i) {
                if (bytes[i] < 0) {// 調整異常數據
                    bytes[i] += 256;
                }
            }
            // 生成jpg圖片
            OutputStream out = new FileOutputStream(imgFilePath);
            out.write(bytes);
            out.flush();
            out.close();
            return true;
        } catch (Exception e) {
            return false;
        }
    }
發佈了41 篇原創文章 · 獲贊 14 · 訪問量 3萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章