def save_uploaded_image(image_data, name_prefix, thumb_size=None): try: image = Image.open(image_data) image.verify() except IOError: raise ValidationError('Invalid image') try: hash = hashlib.md5(image_data.read()).hexdigest() name = "%s-%s.%s" % (name_prefix, hash, image.format.lower()) image_file = File(image_data) image_file.name = name thumb_file = None if thumb_size is not None: # http://www.pythonware.com/library/pil/handbook/image.htm # ...if you need to load the image after using this method, # you must reopen the image file. image_data.seek(0) image = Image.open(image_data) image.thumbnail(thumb_size, Image.ANTIALIAS) temp = StringIO() image.save(temp, format=image.format) temp.seek(0) thumb_file = SimpleUploadedFile( 'thumb-' + name, temp.read(), 'image/%s' % image.format.lower()) # Reset image position image_data.seek(0) return image_file, thumb_file except: raise ValidationError('Could not upload image')
def save_uploaded_image(image_data, name_prefix, thumb_size=None): image_data.seek(0, os.SEEK_END) file_size = image_data.tell() if file_size > settings.MAXIMUM_IMAGE_SIZE: raise ValidationError(trans('The uploaded image is too large')) image_data.seek(0) try: image = Image.open(image_data) image.verify() except IOError: raise ValidationError(trans('Invalid image')) try: hash = hashlib.md5(image_data.read()).hexdigest() name = "%s-%s.%s" % (name_prefix, hash, image.format.lower()) image_file = File(image_data) image_file.name = name thumb_file = None if thumb_size is not None: # http://effbot.org/imagingbook/image.htm # ...if you need to load the image after using this method, # you must reopen the image file. image_data.seek(0) image = Image.open(image_data) image.thumbnail(thumb_size, Image.ANTIALIAS) temp = StringIO() image.save(temp, format=image.format) temp.seek(0) thumb_file = SimpleUploadedFile( 'thumb-' + name, temp.read(), 'image/%s' % image.format.lower()) # Reset image position image_data.seek(0) return image_file, thumb_file except: raise ValidationError(trans('Image upload issue'))