东莞网站建设运营,cargo创建个人网站,企业网站搭建程序,网站建设制作设计优化兰州文章目录 前言一、代码二、测试三、结果 前言
公司项目中用到了实名认证此#xff0c;采用的第三方平台。后端中用到的单项功能为身份证信息人像对比功能#xff0c;在写demo的过程中发现#xff0c;它们所要求的图片信息为base64编码格式。
一、代码
package com.bajiao… 文章目录 前言一、代码二、测试三、结果 前言
公司项目中用到了实名认证此采用的第三方平台。后端中用到的单项功能为身份证信息人像对比功能在写demo的过程中发现它们所要求的图片信息为base64编码格式。
一、代码
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 {/*** 图片转Base64字符串* param imageFileName* return*/public static String convertImageToBase64Str(String imageFileName) {ByteArrayOutputStream baos null;try {//获取图片类型String suffix imageFileName.substring(imageFileName.lastIndexOf(.) 1);//构建文件File imageFile new File(imageFileName);//通过ImageIO把文件读取成BufferedImage对象BufferedImage bufferedImage ImageIO.read(imageFile);//构建字节数组输出流baos new ByteArrayOutputStream();//写入流ImageIO.write(bufferedImage, suffix, baos);//通过字节数组流获取字节数组byte[] bytes baos.toByteArray();//获取JDK8里的编码器Base64.Encoder转为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字符串转图片* 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字符串转为字节数组byte[] bytes Base64.getDecoder().decode(base64String);//构建字节数组输入流bais new ByteArrayInputStream(bytes);//通过ImageIO把字节数组输入流转为BufferedImageBufferedImage bufferedImage ImageIO.read(bais);//构建文件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(----------------------------图片转Base64字符串---------------------------);//图片文件路径String imageFileName C:\\Users\\22.jpg;//图片转Base64字符串String base64Str ConvertImage.convertImageToBase64Str(imageFileName);System.out.println(base64Str);System.out.println(----------------------------Base64字符串转图片---------------------------);//新文件路径String newFileName C:\\Users\\22.jpg;//Base64字符串转图片ConvertImage.convertBase64StrToImage(base64Str, newFileName);System.out.println(生成的文件的路径是newFileName);}三、结果