Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- """Simple Image Grabber using PIL
- Flask==0.10.1
- simplejson==3.8.0
- Pillow==3.1.1
- """
- import uuid
- import io
- import os
- import urllib.request
- from urllib.parse import unquote
- from flask import Flask, send_file, jsonify, request
- from PIL import Image
- app = Flask(__name__)
- request_methods = ['POST', 'GET']
- @app.route('/get_image', methods=request_methods)
- def get_image():
- """
- Get image from URL
- """
- filename = ""
- try:
- filename = unquote(unquote(request_field('url'))).replace(" ", "+")
- req = urllib.request.Request(filename)
- req.add_header('User-agent', 'Mozilla/5.0 (X11; U; Linux i686) \
- Gecko/20071127 Firefox/2.0.0.11')
- url_open = urllib.request.urlopen(req)
- image_file = io.BytesIO(url_open.read())
- image_size = image_file.getbuffer().nbytes
- image_obj = Image.open(image_file)
- image_format = image_obj.format
- if image_format not in ["PNG", "GIF", "JPG", "JPEG"]:
- return jsonify(dict(error='INVALID_FORMAT'))
- # check for min resolution
- if request_field('min_res') and int(request_field('min_res')) > \
- max(image_obj.width, image_obj.height):
- return jsonify(dict(error='LOW_RESOLUTION'))
- if request_field('max_size') and \
- int(request_field('max_size')) < image_size:
- return jsonify(dict(error='LARGE_IMAGE'))
- baseheight = int(request_field('height')) \
- if request_field('height') else 0
- basewidth = int(request_field('width')) \
- if request_field('width') else 0
- if basewidth and baseheight:
- image_obj.thumbnail((basewidth, baseheight), Image.ANTIALIAS)
- elif basewidth and not baseheight:
- wpercent = (basewidth / float(image_obj.size[0]))
- hsize = int((float(image_obj.size[1]) * float(wpercent)))
- image_obj = image_obj.resize((basewidth, hsize), Image.ANTIALIAS)
- elif not basewidth and baseheight:
- wpercent = (baseheight / float(image_obj.size[0]))
- hsize = int((float(image_obj.size[1]) * float(wpercent)))
- image_obj = image_obj.resize((hsize, baseheight), Image.ANTIALIAS)
- unique_filename = uuid.uuid4()
- tmp_file_name = "/tmp/" + str(unique_filename) + \
- "." + image_format.lower()
- image_obj.save(tmp_file_name, image_format, optimize=True, quality=95)
- return send_file(
- tmp_file_name, mimetype='image/' + image_format.lower())
- os.remove(tmp_file_name)
- except:
- return jsonify(dict(error="UNKNOWN"))
- def request_field(var):
- """
- Get values from POST or GET
- """
- if request.method == 'POST' and var in request.form:
- return request.form[var]
- elif var in request.args:
- return request.args.get(var)
- else:
- return None
- if __name__ == "__main__":
- app.run(host='0.0.0.0', port=8000, debug=True)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement