前言
公司項(xiàng)目中用到了實(shí)名認(rèn)證此,采用的第三方平臺(tái)。后端中用到的單項(xiàng)功能為身份證信息人像對(duì)比功能,在寫demo的過程中發(fā)現(xiàn),它們所要求的圖片信息為base64編碼格式。
文章來源:http://www.zghlxwxcb.cn/news/detail-633485.html
一、代碼
package com.bajiao.wyq.tools.chuanglan;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.util.Base64;
import javax.imageio.ImageIO;
public class ConvertImage {
/**
* 圖片轉(zhuǎn)Base64字符串
* @param imageFileName
* @return
*/
public static String convertImageToBase64Str(String imageFileName) {
ByteArrayOutputStream baos = null;
try {
//獲取圖片類型
String suffix = imageFileName.substring(imageFileName.lastIndexOf(".") + 1);
//構(gòu)建文件
File imageFile = new File(imageFileName);
//通過ImageIO把文件讀取成BufferedImage對(duì)象
BufferedImage bufferedImage = ImageIO.read(imageFile);
//構(gòu)建字節(jié)數(shù)組輸出流
baos = new ByteArrayOutputStream();
//寫入流
ImageIO.write(bufferedImage, suffix, baos);
//通過字節(jié)數(shù)組流獲取字節(jié)數(shù)組
byte[] bytes = baos.toByteArray();
//獲取JDK8里的編碼器Base64.Encoder轉(zhuǎn)為base64字符
return Base64.getEncoder().encodeToString(bytes);
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (baos != null) {
baos.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
/**
* Base64字符串轉(zhuǎn)圖片
* @param base64String
* @param imageFileName
*/
public static void convertBase64StrToImage(String base64String, String imageFileName) {
ByteArrayInputStream bais = null;
try {
//獲取圖片類型
String suffix = imageFileName.substring(imageFileName.lastIndexOf(".") + 1);
//獲取JDK8里的解碼器Base64.Decoder,將base64字符串轉(zhuǎn)為字節(jié)數(shù)組
byte[] bytes = Base64.getDecoder().decode(base64String);
//構(gòu)建字節(jié)數(shù)組輸入流
bais = new ByteArrayInputStream(bytes);
//通過ImageIO把字節(jié)數(shù)組輸入流轉(zhuǎn)為BufferedImage
BufferedImage bufferedImage = ImageIO.read(bais);
//構(gòu)建文件
File imageFile = new File(imageFileName);
//寫入生成文件
ImageIO.write(bufferedImage, suffix, imageFile);
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (bais != null) {
bais.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
二、測試
public static void main(String[] args) {
System.out.println("----------------------------圖片轉(zhuǎn)Base64字符串---------------------------");
//圖片文件路徑
String imageFileName = "C:\\Users\\22.jpg";
//圖片轉(zhuǎn)Base64字符串
String base64Str = ConvertImage.convertImageToBase64Str(imageFileName);
System.out.println(base64Str);
System.out.println("----------------------------Base64字符串轉(zhuǎn)圖片---------------------------");
//新文件路徑
String newFileName = "C:\\Users\\22.jpg";
//Base64字符串轉(zhuǎn)圖片
ConvertImage.convertBase64StrToImage(base64Str, newFileName);
System.out.println("生成的文件的路徑是:"+newFileName);
}
三、結(jié)果
文章來源地址http://www.zghlxwxcb.cn/news/detail-633485.html
到了這里,關(guān)于Java中實(shí)現(xiàn)圖片和Base64的互相轉(zhuǎn)化的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!