Skip to content

Instantly share code, notes, and snippets.

@rodrigobertin
Created September 8, 2022 12:48
Show Gist options
  • Save rodrigobertin/5e85f6e0b0a19d31d6caa104cdea17ba to your computer and use it in GitHub Desktop.
Save rodrigobertin/5e85f6e0b0a19d31d6caa104cdea17ba to your computer and use it in GitHub Desktop.
Resize image with orientation
def resize_image(path, filename, rename=None, max_width=1920, quality=80):
"""
Resize image
:param rename:
:param path:
:param filename:
:param max_width:
:param quality:
:return:
"""
try:
img = Image.open(f'{path}/{filename}')
if hasattr(img, '_getexif'):
exif = img._getexif()
if exif:
orientation = None
for tag, label in ExifTags.TAGS.items():
if label == 'Orientation':
orientation = tag
break
if orientation in exif:
if exif[orientation] == 3:
img = img.rotate(180, expand=True)
elif exif[orientation] == 6:
img = img.rotate(270, expand=True)
elif exif[orientation] == 8:
img = img.rotate(90, expand=True)
# create resize
wpercent = (max_width / float(img.size[0]))
hsize = int((float(img.size[1]) * float(wpercent)))
img = img.resize((max_width, hsize), Image.ANTIALIAS)
if rename is not None:
img.save(f'{path}/{rename}', quality=quality)
else:
img.save(f'{path}/{filename}', quality=quality)
except:
pass
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment