Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Test if a file is an image file

Tags:

java

file

io

image

I am using some file IO and want to know if there is a method to check if a file is an image?

like image 860
lancegerday Avatar asked Mar 10 '12 01:03

lancegerday


People also ask

How do you check if a file is a JPG?

If you are having trouble and want to check if you photo is a JPEG, look at the writing under the photo in its file name. If it ends . jpg or . jpeg- then the file is a JPEG and will upload.

How can you tell if a file is a PNG?

Open a file in a Hex editor (or just a binary file viewer). PNG files start with 'PNG', . jpg files should have 'exif'or 'JFIF' somewhere in the beginning.


2 Answers

This works pretty well for me. Hope I could help

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");     } } 
like image 171
Ismael Avatar answered Sep 20 '22 22:09

Ismael


if( ImageIO.read(*here your input stream*) == null)     *IS NOT IMAGE*     

And also there is an answer: How to check a uploaded file whether it is a image or other file?

like image 28
Krystian Avatar answered Sep 18 '22 22:09

Krystian