Created
May 9, 2012 01:11
-
-
Save lucidfrontier45/2640913 to your computer and use it in GitHub Desktop.
Crop 4:3 picture to 16:9 without losing EXIF metadata
This file contains 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
#!/usr/bin/python | |
from PIL import Image | |
from pyexiv2 import ImageMetadata | |
def is16to9(img): | |
img.size | |
return img.size[0] * 9 == img.size[1] * 16 | |
def cropTo16to9(img): | |
original_size = img.size | |
if is16to9(img): | |
cropped_img = img | |
else: | |
width = original_size[0] | |
height = original_size[0] * 9 / 16 | |
upper = (original_size[1] - height) / 2 | |
box = (0, upper, width, upper + height) | |
cropped_img = img.crop(box) | |
return cropped_img | |
def copyExif(src_path, dest_path): | |
if src_path == dest_path: | |
return | |
src_img = ImageMetadata(src_path) | |
src_img.read() | |
dest_img = ImageMetadata(dest_path) | |
dest_img.read() | |
src_img.copy(dest_img) | |
img = Image.open(dest_path) | |
dest_img["Exif.Photo.PixelXDimension"]= img.size[0] | |
dest_img["Exif.Photo.PixelYDimension"]= img.size[1] | |
dest_img.write() | |
import os | |
from optparse import OptionParser | |
parser = OptionParser() | |
parser.add_option("-q", "--quality", type="int", dest="quality", | |
default=100, help="quality of the JPEG compression") | |
parser.add_option("-i", "--input", type="string", dest="ifname", | |
help="inout file name") | |
parser.add_option("-o", "--output", type="string", dest="ofname", | |
help="outout file name") | |
opts, args = parser.parse_args() | |
ifname = opts.ifname | |
quality = opts.quality | |
ofname = opts.ofname | |
if ifname == None: | |
parser.print_help() | |
exit() | |
if ofname == None: | |
basename, ext = os.path.splitext(os.path.basename(ifname)) | |
ofname = basename + "_crp" + ext | |
img = Image.open(ifname) | |
cropped_img = cropTo16to9(img) | |
print img.size | |
print cropped_img.size | |
cropped_img.save(ofname, "JPEG", quality=quality) | |
copyExif(ifname, ofname) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment