Skip to content

Instantly share code, notes, and snippets.

@igorzakhar
Created March 11, 2019 15:58
Show Gist options
  • Save igorzakhar/21a3c532f9fa4a1712efaa3915fd6407 to your computer and use it in GitHub Desktop.
Save igorzakhar/21a3c532f9fa4a1712efaa3915fd6407 to your computer and use it in GitHub Desktop.
import os
from PIL import Image
FILENAME = 'tux.png'
def get_image_data(filename):
try:
return Image.open(filename)
except OSError as error:
return error
def get_resize_value(width, height, ratio=0.5):
new_width = round(width * ratio)
new_height = round(height * ratio)
return new_width, new_height
def resize_image(image_data, new_width, new_height):
return image_data.resize((new_width, new_height), Image.ANTIALIAS)
def save_image(resized_image, original_file):
filename, ext = os.path.splitext(original_file.filename)
x_size, y_size = resized_image.size
path_to_save = '{}_{}x{}{}'.format(filename, x_size, y_size, ext)
try:
resized_image.save(path_to_save, original_file.format)
except OSError as error:
return error
def main():
img = get_image_data(FILENAME)
img_width, img_height = img.size
new_width, new_height = get_resize_value(img_width, img_height)
resized_img = resize_image(img, new_width, new_height)
error = save_image(resized_img, img)
if isinstance(error, OSError):
print("File save error: ", error.strerror)
sys.exit(error.errno)
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment