Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to check if a file is an png image file,using java

Tags:

java

I am building an automate png to jpg, everything is built, but I have a problem detecting png files. Now I am using the file name: I am checking if the end of the file matches .png but this is not working for png files that do not end with .png.

Any ideas?

like image 793
Gigalala Avatar asked Oct 04 '13 06:10

Gigalala


People also ask

How do I know if a file is PNG?

PNG files start with 'PNG', . jpg files should have 'exif'or 'JFIF' somewhere in the beginning.

How do you know if a file is an image in Java?

getContentType(path)" returns "application/octet-stream",but "URLConnection. guessContentTypeFromName(path)" returns the right mime type. This only checks based on the extension of the file. Non-valid images (other binaries without image content and proper file headers) cannot be detected using this method.

Can Java read PNG?

By default, Java supports only these five formats for images: JPEG, PNG, BMP, WEBMP, GIF. If we attempt to work with an image file in a different format, our application will not be able to read it and will throw a NullPointerException when accessing the BufferedImage variable.

How do I know if my image is uploaded or not?

Just check if it starts with image/ . String fileName = uploadedFile. getFileName(); String mimeType = getServletContext(). getMimeType(fileName); if (mimeType.


2 Answers

u can try this

import javax.activation.MimetypesFileTypeMap;
import java.io.File;

class GetMimeType {
  public static void main(String args[]) {
    File f = new File(filePath);
    System.out.println("Mime Type of " + f.getName() + " is " +
                         new MimetypesFileTypeMap().getContentType(f));

}

or

try

public String getContentType(File file) throws IOException {
        return Files.probeContentType(file.getAbsolutePath());
}
like image 109
Rijo Joseph Avatar answered Oct 12 '22 02:10

Rijo Joseph


You can check the header of the file.
See http://en.wikipedia.org/wiki/Portable_Network_Graphics#File_header.

like image 23
Itay Karo Avatar answered Oct 12 '22 02:10

Itay Karo