1. 程式人生 > >base64與圖片檔案之間的互轉

base64與圖片檔案之間的互轉

通常網路傳輸圖片採用base64 格式,因此在程式設計時遇到了藥將圖片檔案讀取成base64 的格式,和將base64格式的字串轉化為圖片的情況

下面是我寫的工具類

注:base64轉圖片時需要先去掉字首

package com.sharetime.util;

import com.ctc.wstx.util.StringUtil;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

import java.io.*;

/**
 * @Author: yd
 * @Date: 2018/7/29 11:05
 * @Version
1.0 */
public class Base64Utils { /** * 將圖片檔案轉換成base64字串,引數為該圖片的路徑 * * @param imageFile * @return java.lang.String */ public String ImageToBase64(String imageFile) { InputStream in = null; byte[] data = null; // 讀取圖片位元組陣列 try { in = new
FileInputStream(imageFile); data = new byte[in.available()]; in.read(data); in.close(); } catch (IOException e) { e.printStackTrace(); } // 對位元組陣列Base64編碼 BASE64Encoder encoder = new BASE64Encoder(); if (data != null
) { return "data:image/jpeg;base64," + encoder.encode(data);// 返回Base64編碼過的位元組陣列字串 } return null; } /** * 將base64解碼成圖片並儲存在傳入的路徑下 * 第一個引數為base64 ,第二個引數為路徑 * * @param base64, imgFilePath * @return boolean */ public boolean Base64ToImage(String base64, String imgFilePath) { // 對位元組陣列字串進行Base64解碼並生成圖片 if (base64 == null) // 影象資料為空 return false; BASE64Decoder decoder = new BASE64Decoder(); try { // Base64解碼 byte[] b = decoder.decodeBuffer(base64); for (int i = 0; i < b.length; ++i) { if (b[i] < 0) {// 調整異常資料 b[i] += 256; } } OutputStream out = new FileOutputStream(imgFilePath); out.write(b); out.flush(); out.close(); return true; } catch (Exception e) { return false; } } /** * 用來測試工具類是否成功 * * @param args * @return void */ public static void main(String[] args) { String path = "C:/Users/YD/Pictures/1.jpg"; Base64Utils base64Utils = new Base64Utils(); String s = base64Utils.ImageToBase64(path); System.out.println(s); String newpath = "C:/Users/YD/Pictures/asd.jpg"; boolean b = base64Utils.Base64ToImage(s, newpath); System.out.println(b); } }

注:還需要注意的一點是,在網站上src=base64的格式也可以將圖片顯示出來,但是在圖片的前面需要加入標識data:image/jpeg;base64

因此在服務端獲取到網頁傳過來的base64字串時要注意是否包含字首如果包含字首則需要去掉在進行轉換

image為從網路傳過來的base64格式的字串

int i = image.indexOf("base64,")+7;//獲取字首data:image/gif;base64,的座標
        String newImage = image.substring(i, image.length());//去除字首