个人公众号,欢迎关注
import sun.misc.BASE64Decoder;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.util.UUID;
public class ImageUtils {
public static String convertBase64ToImage(String base64) {
String[] parts = base64.split(",");
String imageString = parts[1];
// create a buffered image
BufferedImage image;
byte[] imageByte;
BASE64Decoder decoder = new BASE64Decoder();
try {
imageByte = decoder.decodeBuffer(imageString);
} catch (IOException e) {
return null;
}
try (ByteArrayInputStream bis = new ByteArrayInputStream(imageByte)) {
image = ImageIO.read(bis);
} catch (IOException e) {
return null;
}
// write the image to a file
final String uuid = UUID.randomUUID().toString();
final String pathname = "/tmp/" + uuid;
File outputFile = new File(pathname);
try {
outputFile.createNewFile();
} catch (IOException e) {
return null;
}
try {
final boolean write = ImageIO.write(image, parts[0].split("/")[1].split(";")[0], outputFile);
System.out.println(write);
} catch (IOException e) {
return null;
}
return pathname;
}
}