Skip to content

Instantly share code, notes, and snippets.

@ahankinson
Created March 15, 2023 13:55
Show Gist options
  • Save ahankinson/47509dca2ee14e4b1eb61c1abdd01ac8 to your computer and use it in GitHub Desktop.
Save ahankinson/47509dca2ee14e4b1eb61c1abdd01ac8 to your computer and use it in GitHub Desktop.
import logging
log = logging.getLogger(__name__)
def get_dimensions(img_path: str) -> Tuple[int, int]:
"""
Returns a tuple (w, h) of an image with a given ID. Reads the w/h data directly
from the JPEG 2000 header.
:param img_path: a path to a JPEG 2000 image
:return: A tuple containing the width and height of the image. 0,0 if there was a problem indexing the file
"""
log.debug("Getting dimensions for %s", img_path)
width: int = 0
height: int = 0
try:
f = open(img_path, 'rb')
except FileNotFoundError:
# Log this as a debug message, since we will catch this up the call stack and also include the master file
# from which we found it.
log.debug("%s was not found.", img_path)
return width, height
d = f.read(100)
start_header = d.find(b'ihdr')
if start_header == -1:
log.error("Index error with %s. Malformed JPEG 2000 image. Setting to 0, 0", img_path)
return width, height
hs = start_header + 4
ws = start_header + 8
try:
height = d[hs] * 256 ** 3 + d[hs + 1] * 256 ** 2 + d[hs + 2] * 256 + d[hs + 3]
width = d[ws] * 256 ** 3 + d[ws + 1] * 256 ** 2 + d[ws + 2] * 256 + d[ws + 3]
except IndexError:
# If there was a problem reading the JP2, allow the process to continue. It should be easy to identify
# failed images later as they will be the ones with w,h as 0,0.
log.error("Index error with %s. Could not find width and height. Setting to 0, 0.", img_path)
finally:
f.close()
return width, height
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment