Java checks image header

I have one requirement when I need to identify the type of image not by file extension, but by checking the header. I am trying to check a jpeg file by checking a magic number.

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 satisfied at all. ba[i]returns -1.

What am I doing wrong?

+5
source share
1 answer

Java byte -128 127, , ba[0] -1, 0xFF int 255. 0xFF &, , :

    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");
        }

, , , wikipedia , JPEG :

JPEG FF D8 FF D9

FF E0 JFIF, ,

, :

        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");
        }
+2

All Articles