❤️java实现将图片读取成base64字符串,将base64字符串存储为图片
方法一
package org.jeecg.utils;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.util.Base64;
public class Base64ImageUtils {
public static String convertImageToBase64Str(String imageFileName) {
ByteArrayOutputStream baos = null;
try {
String suffix = imageFileName.substring(imageFileName.lastIndexOf(".") + 1);
File imageFile = new File(imageFileName);
BufferedImage bufferedImage = ImageIO.read(imageFile);
baos = new ByteArrayOutputStream();
ImageIO.write(bufferedImage, suffix, baos);
byte[] bytes = baos.toByteArray();
return Base64.getEncoder().encodeToString(bytes);
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (baos != null) {
baos.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
public static void convertBase64StrToImage(String base64String, String imageFileName) {
ByteArrayInputStream bais = null;
try {
String suffix = imageFileName.substring(imageFileName.lastIndexOf(".") + 1);
byte[] bytes = Base64.getDecoder().decode(base64String);
bais = new ByteArrayInputStream(bytes);
BufferedImage bufferedImage = ImageIO.read(bais);
File imageFile = new File(imageFileName);
ImageIO.write(bufferedImage, suffix, imageFile);
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (bais != null) {
bais.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
方法二
package org.jeecg.utils;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;
import java.io.*;
public class Base64StrToImageUtils {
public static void main(String[] args) {
String base64Str = imageToBase64Str("E:\\1.jpeg");
System.out.println(base64Str);
boolean b = base64StrToImage(base64Str, "E:\\002.jpg");
System.out.println(b);
}
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);
}
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;
}
}
}