Java 通过 base64 判断图片格式
Java 通过 base64 判断图片格式
// base64字符串转写为文件
public static void convertBase64DataToImage(String base64ImgData, String filePath) throws IOException {
Files.write(Paths.get(filePath), Base64.getDecoder().decode(base64ImgData), StandardOpenOption.CREATE);
}
// 将文件转写为base64字符串
public static String convertImageToBase64Data(String filePath) throws IOException {
byte[] b = Files.readAllBytes(Paths.get(filePath));
return Base64.getEncoder().encodeToString(b);
}
//判断图片base64字符串的文件格式
public static String checkImageBase64Format(String base64ImgData) {
byte[] b = Base64.getDecoder().decode(base64ImgData);
String type = "";
if (0x424D == ((b[0] & 0xff) << 8 | (b[1] & 0xff))) {
type = "bmp";
} else if (0x8950 == ((b[0] & 0xff) << 8 | (b[1] & 0xff))) {
type = "png";
} else if (0xFFD8 == ((b[0] & 0xff) << 8 | (b[1] & 0xff))) {
type = "jpg";
}
return type;
}
public static String checkImageType(String base64Image) {
// 将Base64字符串解码为字节数组
byte[] imageBytes = Base64.getDecoder().decode(base64Image);
// 检查JPEG格式
if (imageBytes.length >= 2 && imageBytes[0] == (byte) 0xFF && imageBytes[1] == (byte) 0xD8) {
return "JPEG";
}
// 检查PNG格式
if (imageBytes.length >= 8 &&
imageBytes[0] == (byte) 0x89 && imageBytes[1] == (byte) 0x50 &&
imageBytes[2] == (byte) 0x4E && imageBytes[3] == (byte) 0x47 &&
imageBytes[4] == (byte) 0x0D && imageBytes[5] == (byte) 0x0A &&
imageBytes[6] == (byte) 0x1A && imageBytes[7] == (byte) 0x0A) {
return "PNG";
}
// 检查GIF格式
if (imageBytes.length >= 4 &&
imageBytes[0] == (byte) 0x47 && imageBytes[1] == (byte) 0x49 &&
imageBytes[2] == (byte) 0x46 && imageBytes[3] == (byte) 0x38) {
return "GIF";
}
// 未知格式
return "Unknown";
}
public static void main(String[] args) {
File file = urlToFile("https://prod-read.oss-cn-shanghai.aliyuncs.com/img/2024-08-01/1722504255159.png");
String base64 = null;
InputStream in = null;
try {
in = new FileInputStream(file);
byte[] bytes = new byte[(int) file.length()];
in.read(bytes);
base64 = new String(org.apache.commons.codec.binary.Base64.encodeBase64(bytes),"UTF-8");
System.out.println("将文件[]转base64字符串:"+ base64);
String s = checkImageType(base64);
System.out.println("文件类型:" + s);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
作者:肃清万里,总齐八荒