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

Question:

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

If possible, without installing a heavy image library.

Asked By: Marcel

||

Answers:

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'x00x00x00x0Cx6Ax50x20x20x0Dx0Ax87x0A' or magic[:4] == b'xFFx4FxFFx51':
        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.

Answered By: Michael M.
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.