Skip to content

Instantly share code, notes, and snippets.

@arvinsim
Created March 17, 2015 01:55
Show Gist options
  • Save arvinsim/601c808aefe656bc68b6 to your computer and use it in GitHub Desktop.
Save arvinsim/601c808aefe656bc68b6 to your computer and use it in GitHub Desktop.
Check if a file is valid PNG
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
import argparse
from PIL import Image
# Get filename from arguments
parser = argparse.ArgumentParser(description='get arguments')
parser.add_argument('filename')
args = parser.parse_args()
print args.filename
# Check if file exists
if not os.path.isfile(args.filename):
raise IOError('Is not a file')
# TODO: Check if file is valid png
im = Image.open(args.filename)
im.verify()
@cooperdk
Copy link

cooperdk commented May 5, 2021

You can do this without requiring PIL. Simply get the file contents and match the first chars ([:8]) with "\x89PNG\r\n\x1a\n" and char [12:16] with "IHDR".

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment