I am using some file IO
and want to know if there is a method to check if a file is an image?
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.
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.
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"); } }
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?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With