Java validate image header

允我心安 提交于 2019-12-10 14:55:43

问题


I am having one requirement where i need to identify the type of the image not by the files extension but by validating the header. I am trying to validate a JPEG file by magic number validation.

File imgFile =
   new File("C:\\Users\\Public\\Pictures\\Sample Pictures\\Chrysanthemum.jpg");
byte[] ba = Files.toByteArray(imgFile); //Its a google guava library
int i = 0; 
if(ba [i] == 0xFF && ba[i+1] == 0xD8 && ba[i+2] == 0xFF && ba[i+3] == 0xE0){
   System.out.println("isJPEG");
}

But the condition is not getting satisfied at all. ba[i] returns -1.

What am I doing wrong?


回答1:


In Java the byte primitive is signed and has a range from -128 to 127, which means your ba[0] comes out as -1, whereas 0xFF is interpreted as an int as 255. If you do a bitwise AND with 0xFF using the & operator this converts the signed byte to the correct value and your code will work, as follows:

    File imgFile =
           new File("C:\\Users\\Public\\Pictures\\Sample Pictures\\Chrysanthemum.jpg");
        byte[] ba = Files.toByteArray(imgFile); //Its a google guava library
        int i = 0; 
        if((ba [i] & 0xFF) == 0xFF && (ba[i+1] & 0xFF) == 0xD8 && (ba[i+2] & 0xFF) == 0xFF 
           && (ba[i+3] & 0xFF) == 0xE0) {
           System.out.println("isJPEG");
        }

I'm not sure about the exact logic you are using however, as wikipedia states that the magic numbers for JPEGs are as follows:

JPEG image files begin with FF D8 and end with FF D9

FF E0 is JFIF specific, so you may want to double check why you are checking for this

The following would be the code to use to make the checks as per Wikipedia:

        File imgFile =                 
                    new File("C:\\Users\\Public\\Pictures\\Sample Pictures\\Chrysanthemum.jpg");
        byte[] ba = Files.toByteArray(imgFile); //Its a google guava library
        int i = 0; 
        if((ba [i] & 0xFF) == 0xFF && (ba[i+1] & 0xFF) == 0xD8 && (ba[ba.length - 2] & 0xFF) == 0xFF 
           && (ba[ba.length - 1] & 0xFF) == 0xD9) {
           System.out.println("isJPEG");
        }


来源:https://stackoverflow.com/questions/15542775/java-validate-image-header

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!