Open Image From Online, Save To Server Flask
When saving in image from an object without a filename, like a StringIO
object, you need to tell PIL what type of image it is:
img.save(os.path.join(app.config['UPLOAD_FOLDER'], filename), format='PNG')
Here I stated that the format is a PNG, but you'll need to introspect the Content-Type
header from the response and see what type is from that. Map the content type to the appropriate PIL format, based on the header.
You'll also need to come up with a better filename; img.filename
is an empty string as you never gave img.open()
a filename. Use the last component of URL
instead for example; presumably that'll have a filename:
formats = { 'image/jpeg': 'JPEG', 'image/png': 'PNG', 'image/gif': 'GIF'}response = urllib.urlopen(URL)image_type = response.info().get('Content-Type')try: format = formats[image_type]except KeyError: raise ValueError('Not a supported image format')file = cStringIO.StringIO(response.read())img = Image.open(file)# ...filename = secure_filename(URL.rpartition('/')[-1])img.save(os.path.join(app.config['UPLOAD_FOLDER'], filename), format=format)