Last active
December 4, 2018 06:20
-
-
Save jslay88/00da94064b896d118d091396335a7814 to your computer and use it in GitHub Desktop.
Flask - Return Resized Proxied Image
This file contains 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
from PIL import Image | |
from io import BytesIO | |
from flask import send_file | |
from urllib.request import urlopen | |
from tempfile import NamedTemporaryFile | |
from urllib.error import URLError, HTTPError, ContentTooShortError | |
@web.route('/snapshot') | |
def snapshot(): | |
""" | |
Proxy an image, resize, and return as file attachment | |
Optional URL Params: ?width=int&height=int | |
:return: Resized (if defined) proxied image. | |
""" | |
try: | |
url = 'http://10.3.0.50:8080/?action=snapshot' # URL of proxied image. | |
img = Image.open(BytesIO(urlopen(url).read())) | |
img = img.resize((int(request.args.get('width', img.size[0])), | |
int(request.args.get('height', img.size[1])))) | |
return_image = NamedTemporaryFile(mode='w+b', suffix='.jpg') | |
img.save(return_image) | |
img.close() | |
return_image.seek(0, 0) | |
return send_file(return_image, attachment_filename='snapshot.jpg') | |
except (URLError, HTTPError, ContentTooShortError, ValueError): | |
return '', 404 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment