Skip to content

Instantly share code, notes, and snippets.

@timokoola
Created August 23, 2017 12:58
Show Gist options
  • Select an option

  • Save timokoola/1de11e8c36778ab579cb9fc407c41c6e to your computer and use it in GitHub Desktop.

Select an option

Save timokoola/1de11e8c36778ab579cb9fc407c41c6e to your computer and use it in GitHub Desktop.
Snippet to (crudely) resize images in a directory and upload to a S3 bucket
import os
from PIL import Image
desired_w = 300.0
bucket_name = "mybucket"
files = [x for x in os.listdir() if x.endswith("jpg")]
for i in files:
img = Image.open(i)
si = os.stat(i)
new_name = i.split(".")[0].replace(" ", "_").replace("-","").lower() + "_smaller.jpg"
old_size = img.size
scale_by = desired_w / img.size[0]
new_size = (int(old_size[0] * scale_by), int(old_size[1] * scale_by))
new_img = img.resize(new_size)
new_img.save(new_name)
ns = os.stat(new_name)
print(i + " " + str(old_size) + " " + str(si.st_size // 1024) + "kB -> " + new_name + " " + str(new_size) + " " + str(ns.st_size // 1024) + "kB")
import boto3
client = boto3.client("s3")
small_files = [x for x in os.listdir() if x.find("smaller") != -1]
for sf in small_files:
with open(sf, 'rb') as data:
client.upload_fileobj(data, bucket_name, sf)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment