Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- 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)
Add Comment
Please, Sign In to add comment