Reputation: 2526
I'm trying to upload image and have a validation that checks first bytes in order to detect what format image has (jpg or png in my case). I'm using spring MultipartFile to upload an image. Wikipedia tells that .PNG has 89 50 4E 47 0D 0A 1A 0A and .JPG has FF D8 marks respectively. I'm trying to get bytes of image that is within MultipartFile:
CommonsMultipartFile logo = request.getFile('logo')...
byte[] byteArray = logo.getBytes();
but when I'm debugging I see that byteArray doesn't contain those masks. For example, I tried to upload .JPG image and first bytes were -1 40 and with .PNG first bytes were -119 80 78 71 13 10 26 10 0. But what is interesing that if to save image like that:
logo.transferTo(new File(...))
to file system and check byte representation of image with Hex Editor then all is OK - for both .PNG and .JPEG there are proper byte marks (89 50 4E 47 0D 0A 1A 0A and FF D8)
I also tried logo.getFileItem().get()
instead of logo.getBytes()
but it didn't help.
I would really appreciate any help. Thank you!
Upvotes: 0
Views: 1205
Reputation: 20069
You need to account for the difference in representation. When using System.out.println() (or a debugger) you see the decimal representation of the signed byte(s). In a hex editor you see the same in hexadecimal.
How are you checking for "match" in your code?
Edit: Comparing a byte to an int literal (thats what the 0x notation is to the compiler) requires masking the byte with 0xFF (to suppress sign extension; the compiler casts the bytes to int for comparing. Thats just how java works with the signed byte type).
Possible ways to express the comparison are (byteArray[] & 0xFF) == 0xXX
or byteArray[] == (byte) 0xXX
. Just writing byteArray[] == 0xXX
means literally sign extend the byte to int, then compare to int literal.
Upvotes: 1