工作中调用第三方接口的时候,比如(人脸识别,身份证识别,文字识别等等)有时是图片,有时是Base64的字符串,一般前端上传的都是图片,我们有时就需要进行相应的转换了。
我们也写一个工具类,完成这两个转化,需要注意的是,本文中的版本:
pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0modelVersion>
<parent>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-parentartifactId>
<version>2.6.0version>
<relativePath/>
parent>
<groupId>com.aliangroupId>
<artifactId>ImageToBase64artifactId>
<version>0.0.1-SNAPSHOTversion>
<name>ImageToBase64name>
<description>图片和Base64之间的相互转化description>
<properties>
<java.version>1.8java.version>
properties>
<dependencies>
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starterartifactId>
dependency>
dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-maven-pluginartifactId>
plugin>
plugins>
build>
project>
ImageUtil.java
package com.alian.imagetobase64.utils;
import javax.imageio.ImageIO;
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;
public class ImageUtil {
/**
* 图片转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把字节数组输入流转为BufferedImage
BufferedImage 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();
}
}
}
}
图片和Base64之间的相互转化我代码的解释已经很清楚了,有兴趣的可以仔细看看,我们这里并没有引用大篇幅的依赖获取其他的工具类,都是基于已有的环境实现。
简单写个main方法测试下
public static void main(String[] args) {
System.out.println("----------------------------图片转Base64字符串---------------------------");
//图片文件路径
String imageFileName = "C:\\myFile\\CSDN\\imageToBase64\\csdn.jpg";
//图片转Base64字符串
String base64Str = ImageUtil.convertImageToBase64Str(imageFileName);
System.out.println(base64Str);
System.out.println("----------------------------Base64字符串转图片---------------------------");
//新文件路径
String newFileName = "C:\\myFile\\CSDN\\imageToBase64\\csdn-new.jpg";
//Base64字符串转图片
ImageUtil.convertBase64StrToImage(base64Str, newFileName);
System.out.println("生成的文件的路径是:"+newFileName);
}
运行结果:
----------------------------图片转Base64字符串---------------------------
/9j/4AAQSkZJRgABAgAAAQABAAD/2wBDAAgGBgcGBQgHBwcJCQgKDBQNDAsLDBkSEw8UHRofHh0aHBwgJC4nICIsIxwcKDcpLDAxNDQ0Hyc5PTgyPC4zNDL/2wBDAQkJCQwLDBgNDRgyIRwhMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjL/wAARCAEAAQADASIAAhEBAxEB/8QAHwAAAQUBAQEBAQEAAAAAAAAAAAECAwQFBgcICQoL/8QAtRAAAgEDAwIEAwUFBAQAAAF9AQIDAAQRBRIhMUEGE1FhByJxFDKBkaEII0KxwRVS0fAkM2JyggkKFhcYGRolJicoKSo0NTY3ODk6Q0RFRkdISUpTVFVWV1hZWmNkZWZnaGlqc3R1dnd4eXqDhIWGh4iJipKTlJWWl5iZmqKjpKWmp6ipqrKztLW2t7i5usLDxMXGx8jJytLT1NXW19jZ2uHi4+Tl5ufo6erx8vP09fb3+Pn6/8QAHwEAAwEBAQEBAQEBAQAAAAAAAAECAwQFBgcICQoL/8QAtREAAgECBAQDBAcFBAQAAQJ3AAECAxEEBSExBhJBUQdhcRMiMoEIFEKRobHBCSMzUvAVYnLRChYkNOEl8RcYGRomJygpKjU2Nzg5OkNERUZHSElKU1RVVldYWVpjZGVmZ2hpanN0dXZ3eHl6goOEhYaHiImKkpOUlZaXmJmaoqOkpaanqKmqsrO0tba3uLm6wsPExcbHyMnK0tPU1dbX2Nna4uPk5ebn6Onq8vP09fb3+Pn6/9oADAMBAAIRAxEAPwD3+iiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKK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qB2AHQVBqGk6dq0Ih1LT7W9iByEuYVkUfgwNdkVyxSPka1T2tWVTu2/vPjymNDE5y0aMfUqDX1Bc/CnwTdOWfQ0TPaCeWJR9AjACqf/CmPBOc/2fdfT7dN/wDFVRmfNwAAwOB6U+GKW5uEtreKSa4k4SGJC7ufZRyfwr6Zt/hP4Jt3DLogYjtNczSA/UM5BrptO0fTNIiaLTNOtLKNuq20Cxg/UKBQB4j4I+D17f3EN/4miNrYqQwsif3s/fD4+4vqPvdQQte9IixIERQqqMKqjAA9BT6KAPkrxncG68c69KTk/wBoTpn/AHXKj9FFYdfW934U8O30ry3mg6XcSOSzPNZxuWJ5JJI61Rb4deDXJJ8M6YpP9y3Vf5UAfK1B45NfU4+G/g0HP/CO2JHo0eR+Rq5beDPC1m6vbeG9JideQ6WUYYfjjNAHy5o+hat4hkCaPptzfZON8KZRT/tOflX8SK9k8EfByHTZotR8StFdXSEPFZx/NFGfVyR85HHH3Qc/e4I9bAAAAAAHQCnUAFfM3xk1CKb4l3kck0atbW8MGC2MDb5n/tQ19M1E1vC7FmhjZj1JUEmgD4rlu4UhdlmiLBSQN45NfZ2m2i6fpVnZL923gSIfRVA/pUv2W3/594v++BU1ABXn3xou47X4a3iO4Q3Fxbxgk46Sq5/RDXoNMeNJF2uqsOuGGaAPiz7Vb/8APeL/AL7Fe0fs/ojyeIrlGVwRbRgqQcY80n+Yr2j7Lb/88Iv++BTkijiB2IqZ67RigCSiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigD/9k=
----------------------------Base64字符串转图片---------------------------
生成的文件的路径是:C:\myFile\CSDN\imageToBase64\csdn-new.jpg
效果图
从上图的标注上我们可以看到生成的图片变大了,这是因为当把数据进行Base64编码后,生成的数据会比原数据大三分之一。关于Base64编码还有不懂的,可以参考我另外一篇文章:Java实现Base64工具类(编码和解码)