Home > database >  How to check if an image is "JPEG 2000" in Python?
How to check if an image is "JPEG 2000" in Python?

Time:12-21

How to check if an image file is JPEG 2000 in Python?

If possible, without installing a heavy image library.

CodePudding user response:

If the image is stored as a file, you can check if it starts with the JPEG 2000 magic number, 00 00 00 0C 6A 50 20 20 0D 0A 87 0A or FF 4F FF 51. Just like this:

with open('image.jp2', 'rb') as file:
    magic = file.read(12)
    if magic == b'\x00\x00\x00\x0C\x6A\x50\x20\x20\x0D\x0A\x87\x0A' or magic[:4] == b'\xFF\x4F\xFF\x51':
        print('File is JPEG 2000')
    else:
        print('File is not JPEG 2000')

If the image is not stored as a file, then you can easily adapt this code. All you need to do is check if the first 12 or 4 bytes match the magic number.

  • Related