/**
* 是否是 png
* @param file
* @return
*/
public boolean isPngFile(MultipartFile file) {
return isPngFileByExtension(file) && isPngFileByContent(file);
}
/**
* 通过文件扩展名检查
* @param file
* @return
*/
public boolean isPngFileByExtension(MultipartFile file) {
String fileName = file.getOriginalFilename();
return fileName != null && fileName.toLowerCase().endsWith(".png");
}
/**
* 通过文件内容检查
* @param file
* @return
*/
public boolean isPngFileByContent(MultipartFile file) {
byte[] pngSignature = new byte[]{(byte) 0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A};
byte[] signatureBytes = new byte[8];
try (InputStream inputStream = file.getInputStream()) {
if (inputStream.read(signatureBytes) == 8) {
if (Arrays.equals(signatureBytes, pngSignature)) {
return true;
}
}
} catch (IOException e) {
LoggerUtil.error("通过文件内容检查图片是否是png格式出错",e);
}
return false;
}
07-28
1万+
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)