Created
September 19, 2018 19:34
-
-
Save rechner/fbe3e215630f73dbca60a595bd1dfdfa to your computer and use it in GitHub Desktop.
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
#!/usr/bin/env python3 | |
from flask import Flask, Response, abort, request | |
from PIL import Image | |
import requests | |
try: | |
from StringIO import BytesIO | |
except ImportError: | |
from io import BytesIO | |
MAX_IMAGE_SIZE = 5 * 1024 * 1024 | |
app = Flask(__name__) | |
app.config.from_object(__name__) | |
@app.route('/') | |
def index(): | |
return Response("Use /convert?url=<image url>") | |
@app.route('/convert') | |
def convert_image(): | |
url = request.args.get('url', None) | |
if url is None: | |
abort(401) | |
try: | |
remote_image = requests.get(url) | |
if not remote_image.ok: | |
abort(401) | |
except requests.RequestException: | |
abort(401) | |
image_f = BytesIO(remote_image.content) | |
image_f.seek(0) | |
original = Image.open(image_f) | |
if image_f.getbuffer().nbytes >= MAX_IMAGE_SIZE: | |
# Cut that sucker in half | |
half = lambda x: int(x / 2) | |
original = original.resize(map(half, original.size), Image.ANTIALIAS) | |
converted = BytesIO() | |
original.save(converted, "JPEG", optimize=True, quality=90) | |
converted.seek(0) | |
print(converted.getbuffer().nbytes / (1024 * 1024)) | |
return Response(converted, mimetype="image/jpeg") | |
if __name__ == '__main__': | |
app.run(host='0.0.0.0') | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment