温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

Java中怎么将base64编码字符串转换为图片

发布时间:2023-03-17 16:27:30 来源:亿速云 阅读:89 作者:iii 栏目:开发技术

本篇内容介绍了“Java中怎么将base64编码字符串转换为图片”的有关知识,在实际案例的操作过程中,不少人都会遇到这样的困境,接下来就让小编带领大家学习一下如何处理这些情况吧!希望大家仔细阅读,能够学有所成!

将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;
        }
    }
 
}

“Java中怎么将base64编码字符串转换为图片”的内容就介绍到这里了,感谢大家的阅读。如果想了解更多行业相关的知识可以关注亿速云网站,小编将为大家输出更多高质量的实用文章!

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI