我正在使用一些文件IO
,想知道是否有一种方法可以检查一个文件是否为图像?
这对我来说非常有效。希望我能帮到你。
import javax.activation.MimetypesFileTypeMap;
import java.io.File;
class Untitled {
public static void main(String[] args) {
String filepath = "/the/file/path/image.jpg";
File f = new File(filepath);
String mimetype= new MimetypesFileTypeMap().getContentType(f);
String type = mimetype.split("/")[0];
if(type.equals("image"))
System.out.println("It's an image");
else
System.out.println("It's NOT an image");
}
}
if( ImageIO.read(*here your input stream*) == null)
*IS NOT IMAGE*
还有一个答案:如何检查上传的文件是图像还是其他文件?
<X>/image
的形式出现。你可以尝试类似这样的方法:
String pathname="abc\xyz.png"
File file=new File(pathname);
String mimetype = Files.probeContentType(file.toPath());
//mimetype should be something like "image/png"
if (mimetype != null && mimetype.split("/")[0].equals("image")) {
System.out.println("it is an image");
}
ImageIO.read
),或使用标准JDK方法(MimetypesFileTypeMap
和Files.probeContentType
)。
如果不需要读取图像,而只是想测试它是否为图像(并可能将其内容类型保存在Content-Type
响应头中,以便将来读取此图像时设置),第一种方法效率不高。
传入的JDK方式通常只测试文件扩展名,不能真正给出您可以信任的结果。
对我有效的方法是使用Apache Tika库。
private final Tika tika = new Tika();
private MimeType detectImageContentType(InputStream inputStream, String fileExtension) {
Assert.notNull(inputStream, "InputStream must not be null");
String fileName = fileExtension != null ? "image." + fileExtension : "image";
MimeType detectedContentType = MimeType.valueOf(tika.detect(inputStream, fileName));
log.trace("Detected image content type: {}", detectedContentType);
if (!validMimeTypes.contains(detectedContentType)) {
throw new InvalidImageContentTypeException(detectedContentType);
}
return detectedContentType;
}
fileExtension
作为提示传递给Tika
。不过,根据文档,它在某些情况下有助于更好地检测。ImageIO.read
相比,此方法的主要优点是Tika
不会将整个文件读入内存,而只读取前几个字节。MimetypesFileTypeMap
和Files.probeContentType
相比,其主要优点是Tika
确实读取了文件的前几个字节,而JDK在当前实现中仅检查文件扩展名。ImageIO.read
。
- 如果您只想检查(并可能存储)真正的Content-Type
,则使用Tika
(本答案)。
- 如果您在可信环境中工作,并且您100%确定文件扩展名正确,则使用prunge's Answer中的Files.probeContentType
。 import javax.activation.MimetypesFileTypeMap;
File myFile;
String mimeType = new MimetypesFileTypeMap().getContentType( myFile ));
// mimeType should now be something like "image/png"
if(mimeType.substring(0,5).equalsIgnoreCase("image")){
// its an image
}
这是基于使用tika的答案的代码。
private static final Tika TIKA = new Tika();
public boolean isImageMimeType(File src) {
try (FileInputStream fis = new FileInputStream(src)) {
String mime = TIKA.detect(fis, src.getName());
return mime.contains("/")
&& mime.split("/")[0].equalsIgnoreCase("image");
} catch (IOException e) {
throw new RuntimeException(e);
}
}