Java编程中base64图片与文件图片的相互转化工具
教程分享
>
Java教程
(2787)
2024-04-17 12:33:25
1.依赖包,maven引入
<!--Base64Encoder等工具类 -->
<dependency>
<groupId>commons-codec</groupId>
<artifactId>commons-codec</artifactId>
<version>1.10</version>
</dependency>
<!--/Base64Encoder等工具类 -->
2.Java编程代码:
package com.leftso.common;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import javax.imageio.ImageIO;
import org.apache.commons.codec.binary.Base64;
/**
* 图片与base64编码的互转工具
*
* @author leftso
*
*/
public class ImageBase64Util {
public static void main(String[] args) {
try {
File image = new File("C:\\Users\\fghfghdf\\Desktop\\temp\\2.png");
String imageStr = image2Base64(new FileInputStream(image));
System.out.println(imageStr);
File out = new File("C:\\Users\\fghfghdf\\Desktop\\temp\\3.png");
base642Image(imageStr, new FileOutputStream(out));
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 图片文件转换为base64编码的串
*
* @param imageFileInputStream
* 图片文件输入流
* @return 编码后的base64串
* @throws IOException
* 可能出现IO异常
*/
public static String image2Base64(InputStream imageFileInputStream) throws IOException {
byte[] data = new byte[imageFileInputStream.available()];
imageFileInputStream.read(data);
imageFileInputStream.close();
Base64 base64 = new Base64();
return base64.encodeAsString(data);
}
/**
* base64串转换为图片文件
*
* @param base64Image
* 图片base64串
* @param outputStream
* 输出流
* @throws IOException
* 可能出现IO异常
*/
public static void base642Image(String base64Image, OutputStream outputStream) throws IOException {
Base64 base64 = new Base64();
// 解码
byte[] imageArr = base64.decode(base64Image);
InputStream sbs = new ByteArrayInputStream(imageArr);
BufferedImage bufferImg = ImageIO.read(sbs);
ImageIO.write(bufferImg, "PNG", outputStream);
}
}
注意
前端传递过来的图片,一般会有一个前缀,如下
"data:image/jpeg;base64,"
解码之前去掉,否则错误。
https://www.leftso.com/article/97.html