base64编码字符串和图片的互转

本文介绍了一个实用的Java工具类Base64ImageUtils,用于将图片文件转换为Base64编码字符串,以及将Base64编码字符串还原为图片。通过示例代码展示了如何使用该工具类进行图片的编码和解码。

新建一个Base64ImageUtils类

package com.demo.test;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

public class Base64ImageUtils {

    /**
               * 将base64编码字符串转换为图片
     * @param base64Code
     * @param outputPath
     * @return
     */
	public static boolean generateImage(String base64Code,String outputPath) {
		if (base64Code == null) {
			return false;
		}
		BASE64Decoder decoder = new BASE64Decoder();
		try {
			byte[] b = decoder.decodeBuffer(base64Code);
			for (int i = 0; i < b.length; i++) {
				if (b[i] < 0) {
					b[i]+= 256;
				}
			}
			OutputStream out = new FileOutputStream(outputPath);
			out.write(b);
			out.flush();
			out.close();
			return true;
		} catch (Exception e) {
			return false;
		}
	}
	
    /**
               * 根据图片地址转换为base64编码字符串
     * @param imagePath
     * @return
     */
	
	public static String getBase64Code(String imagePath) {
		InputStream input = null;
		byte[] data = null;
		try {
			input = new FileInputStream(imagePath);
			data = new byte[input.available()];
			input.read(data);
			input.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
		BASE64Encoder encoder = new BASE64Encoder();
		return encoder.encode(data);
	}
	
}

测试类:

package com.demo.test;

public class Base64Test {

	public static void main(String[] args) {
		String base64Code = Base64ImageUtils.
getBase64Code("F:\\Test\\shop\\WebRoot\\products\\405964b4-bf81-470c-8ee6-fed1aaf35b4194d9458f-6b65-4b1c-9577-0928a4818de0.jpg");//这是你转换的图片路径
		System.out.println(base64Code);
		Base64ImageUtils.
generateImage(base64Code, "C:\\Users\\zhangjie\\Desktop\\psb.webp1.jpg");//这是你获取的Base64编码在生成一个新的图片的路径名
		
	}
}

图片转换器的地址:http://imgbase64.duoshitong.com

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

奋斗的小虾米

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值