import javax.imageio.stream.FileImageOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Base64;
/**
* @author: sizzled
* @createTime: 2023/01/08 21:30
* @description:
* @version: v1.0
*/
public class ImgHelper {
/**
* TODO:将byte数组以Base64方式编码为字符串
*
* @param bytes 待编码的byte数组
* @return 编码后的字符串
*/
public static String encode(byte[] bytes) {
return Base64.getEncoder().encodeToString(bytes);
}
/**
* TODO:将以Base64方式编码的字符串解码为byte数组
*
* @param encodeStr 待解码的字符串
* @return 解码后的byte数组
*/
public static byte[] decode(String encodeStr) {
byte[] bt = null;
bt = Base64.getDecoder().decode(encodeStr);
return bt;
}
/**
* TODO:将两个byte数组连接起来后,返回连接后的Byte数组
*
* @param front 拼接后在前面的数组
* @param after 拼接后在后面的数组
* @return 拼接后的数组
*/
public static byte[] connectBytes(byte[] front, byte[] after) {
byte[] result = new byte[front.length + after.length];
System.arraycopy(front, 0, result, 0, after.length);
System.arraycopy(after, 0, result, front.length, after.length);
return result;
}
/**
* TODO:将图片以Base64方式编码为字符串
*
* @param imgUrl 图片的绝对路径(例如:D:\\jsontest\\abc.jpg)
* @return 编码后的字符串
* @throws IOException
*/
public static String encodeImage(String imgUrl) throws IOException {
FileInputStream fis = new FileInputStream(imgUrl);
byte[] rs = new byte[fis.available()];
fis.read(rs);
fis.close();
return encode(rs);
}
//byte[]转图片
public static void byte2image(byte[] data, String path) {
if (data.length < 3 || path.equals("")) return;
try {
FileImageOutputStream imageOutput = new FileImageOutputStream(new File(path));
imageOutput.write(data, 0, data.length);
imageOutput.close();
} catch (Exception ex) {
ex.printStackTrace();
}
}
/**
* @param args
*/
public static void main(String[] args) {
String str;
try {
str = encodeImage("E:\\2kc-projectSets\\1AllCompany\\01Gener\\gener011-\\jets-aia\\aia-portal-cas-server\\src\\main\\resources\\static\\themes\\portal\\images\\loginbg2.jpeg");
System.out.println(str);
byte[] bytes = decode(str);
byte2image(bytes, "C:\\Users\\Administrator\\Desktop\\a.jpg");
} catch (IOException e) {
e.printStackTrace();
}
}
}
ImgHelper.java 将图片以Base64方式编码为字符串
于 2023-02-01 14:34:01 首次发布
该代码片段展示了如何使用Java进行Base64编码和解码,包括将图片文件转换为Base64字符串以及将Base64字符串还原为图片。ImgHelper类提供了静态方法,用于处理byte数组和Base64字符串之间的转换,并且包含将图片文件读取为字节数组以及将字节数组写入新图片文件的功能。
摘要由CSDN通过智能技术生成