Created
December 13, 2017 17:34
-
-
Save maksymx/d1644ee919c3288079f8a88b34af7c5c to your computer and use it in GitHub Desktop.
Image resize + upload to s3
This file contains hidden or 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
import os | |
from io import BytesIO | |
import boto3 | |
from PIL import Image | |
from django.conf import settings | |
def store_in_bucket(data, key, content_type, public_read=False): | |
boto3.client('s3').put_object( | |
Bucket=settings.STORAGE_BUCKET, | |
Key=key, | |
ContentType=content_type, | |
ACL=('public-read' if public_read else 'private'), | |
Body=data | |
) | |
def store_file_in_bucket(fileobj, key, public_read=False): | |
boto3.client('s3').upload_fileobj( | |
fileobj, settings.STORAGE_BUCKET, key, | |
ExtraArgs=dict( | |
ContentType=guess_content_type(fileobj), | |
ContentDisposition='inline; filename="{}"'.format(fileobj.name), | |
ACL=('public-read' if public_read else 'private') | |
) | |
) | |
def get_bucket_object(key): | |
return boto3.resource('s3').Object(settings.STORAGE_BUCKET, key) | |
def get_signed_bucket_url(key, expire_minutes=10): | |
return boto3.client('s3').generate_presigned_url( | |
'get_object', | |
Params=dict( | |
Bucket=settings.STORAGE_BUCKET, | |
Key=key | |
), | |
ExpiresIn=(expire_minutes * 60) | |
) if key else None | |
class ImageManipulator(object): | |
def resize(self, object_key, max_width): | |
if not max_width: | |
max_width = 640 | |
if not os.path.exists('tmp'): | |
os.makedirs('tmp') | |
temp_dir = os.path.abspath('tmp') | |
obj_path = os.path.join(temp_dir, object_key) | |
obj = get_bucket_object(object_key) | |
obj.download_file(obj_path) | |
in_img = None | |
out_img = BytesIO() | |
try: | |
in_img = Image.open(obj_path, 'r') | |
except IOError: | |
print("Cannot open file {}".format(object_key)) | |
if in_img.width > max_width: | |
in_img.thumbnail((in_img.height, max_width), Image.ANTIALIAS) | |
in_img.save(out_img, in_img.format) | |
out_img.seek(0) | |
out_img.name = object_key | |
store_file_in_bucket(out_img, object_key) | |
os.remove(obj_path) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment