Java中将base64编码字符串转换为图片的代码

前一段时间,在做摄像头拍照上传,摄像头拍的照片为base64编码格式的字符串,需要上传至项目中,则需要使用到将base64编码字符串转换为图片

1、将base64编码字符串转换为图片的代码如下 ImageUtil.java:

package util;

import javax.servlet.http.HttpServletRequest;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Base64;
import java.util.UUID;

public class ImageUtil {

	/**
	 * @Description: 将base64编码字符串转换为图片
	 * @Author:
	 * @CreateTime:
	 * @param file base64编码字符串
	 * @param path 图片路径-具体到文件
	 * @return
	 */
	public static String generateImage(String file, String path, HttpServletRequest request) {
	// 解密
	try {
	// 项目绝对路径
	String savePath = request.getSession().getServletContext().getRealPath("upload");
	// 图片分类路径+图片名+图片后缀
	String imgClassPath = path.concat(UUID.randomUUID().toString()).concat(".jpg");
	// 解密
	Base64.Decoder decoder = Base64.getDecoder();
	// 去掉base64前缀 data:image/jpeg;base64,
	file = file.substring(file.indexOf(",", 1) + 1, file.length());
	byte[] b = decoder.decode(file);
	// 处理数据
	for (int i = 0; i < b.length; ++i) {
	if (b[i] < 0) {
	b[i] += 256;
	}
	}
	// 保存图片
	OutputStream out = new FileOutputStream(savePath.concat(imgClassPath));
	out.write(b);
	out.flush();
	out.close();
	// 返回图片的相对路径 = 图片分类路径+图片名+图片后缀
	return imgClassPath;
	} catch (IOException e) {
	return null;
	}
	}
}

补充:Java实现图片转base64字符串和图片互相转换

import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;
 
import java.io.*;
 
/**
 * @Description:
 * @Author: Han
 * @CreateDate: 2022/9/7
 **/
public class Test010 {
 
 public static void main(String[] args) {
 String base64Str = imageToBase64Str("D:\\SoftWare\\图片素材\\头像\\432.jpeg");
 System.out.println(base64Str);
 
 boolean b = base64StrToImage(base64Str, "D:\\002.jpg");
 System.out.println(b);
 }
 
 /**
 * 图片转base64字符串
 *
 * @param imgFile 图片路径
 * @return
 */
 public static String imageToBase64Str(String imgFile) {
 InputStream inputStream = null;
 byte[] data = null;
 try {
 inputStream = new FileInputStream(imgFile);
 data = new byte[inputStream.available()];
 inputStream.read(data);
 inputStream.close();
 } catch (IOException e) {
 e.printStackTrace();
 }
 // 加密
 BASE64Encoder encoder = new BASE64Encoder();
 return encoder.encode(data);
 }
 
 /**
 * base64编码字符串转换为图片,并写入文件
 *
 * @param imgStr base64编码字符串
 * @param path 图片路径
 * @return
 */
 public static boolean base64StrToImage(String imgStr, String path) {
 if (imgStr == null)
 return false;
 BASE64Decoder decoder = new BASE64Decoder();
 try {
 // 解密
 byte[] b = decoder.decodeBuffer(imgStr);
 // 处理数据
 for (int i = 0; i < b.length; ++i) {
 if (b[i] < 0) {
 b[i] += 256;
 }
 }
 //文件夹不存在则自动创建
 File tempFile = new File(path);
 if (!tempFile.getParentFile().exists()) {
 tempFile.getParentFile().mkdirs();
 }
 OutputStream out = new FileOutputStream(tempFile);
 out.write(b);
 out.flush();
 out.close();
 return true;
 } catch (Exception e) {
 return false;
 }
 }
 
}
作者:Asurplus原文地址:https://lizhou.blog.csdn.net/article/details/105065697

%s 个评论

要回复文章请先登录注册