base64字符串轉化成圖片


package com.dhht.wechat.util;

import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

import java.io.*;

/**
* @Author: sh
* @Description: ImgUtil
* @Date: 9:14 2019/7/1
*/
public class ImgUtil {


/**
* 圖片轉化成base64字符串
*
* @param imgPath
* @return
*/
public static String GetImageStr(String imgPath) {// 將圖片文件轉化為字節數組字符串,並對其進行Base64編碼處理
String imgFile = imgPath;// 待處理的圖片
InputStream in = null;
byte[] data = null;
String encode = null; // 返回Base64編碼過的字節數組字符串
// 對字節數組Base64編碼
BASE64Encoder encoder = new BASE64Encoder();
try {
// 讀取圖片字節數組
in = new FileInputStream(imgFile);
data = new byte[in.available()];
in.read(data);
encode = encoder.encode(data);
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
in.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return encode;
}

/**
* base64字符串轉化成圖片
*
* @param imgData 圖片編碼
* @param imgFilePath 存放到本地路徑
* @return
* @throws IOException
*/
@SuppressWarnings("finally")
public static boolean GenerateImage(String imgData, String imgFilePath) throws IOException { // 對字節數組字符串進行Base64解碼並生成圖片
if (imgData == null) // 圖像數據為空
return false;
BASE64Decoder decoder = new BASE64Decoder();
OutputStream out = null;
try {
out = new FileOutputStream(imgFilePath);
// Base64解碼
byte[] b = decoder.decodeBuffer(imgData);
for (int i = 0; i < b.length; ++i) {
if (b[i] < 0) {// 調整異常數據
b[i] += 256;
}
}
out.write(b);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
out.flush();
out.close();
return true;
}
}
}


免責聲明!

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



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