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?
PNG files start with 'PNG', . jpg files should have 'exif'or 'JFIF' somewhere in the beginning.
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.
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.
Just check if it starts with image/ . String fileName = uploadedFile. getFileName(); String mimeType = getServletContext(). getMimeType(fileName); if (mimeType.
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());
}
You can check the header of the file.
See http://en.wikipedia.org/wiki/Portable_Network_Graphics#File_header.
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