Created
January 26, 2024 16:36
-
-
Save thetonus/6bb09fd3f8c672f7e5b75f8619f42a83 to your computer and use it in GitHub Desktop.
Verify an image in python
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import contextlib | |
from pathlib import PATH | |
from PIL import Image | |
def _is_valid_image(file: Path) -> bool: | |
"""Determine if the image is valid | |
References: https://stackoverflow.com/a/53470882 | |
Args: | |
file: Filename of image | |
Returns: | |
bool: True if image is valid, False otherwise | |
""" | |
try: | |
assert file.exists() # Check for existence | |
assert file.stat().st_size > 0 # Check if there is some data | |
with contextlib.closing(Image.open(file)) as im: | |
# Use PIL to verify image | |
im.verify() | |
with contextlib.closing(Image.open(file)) as im: | |
# Image.verify() will raise an exception if the image is corrupted. | |
# Computing a transformation of the image will raise an exception if the image is corrupted. | |
im.transpose(Image.FLIP_LEFT_RIGHT) | |
return True | |
except Exception: | |
return False |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment