def generate_invalid_chem_csv(self): csv_string = ("data_document_id,data_document_filename," "prod_name,doc_date,rev_num,raw_category,raw_cas,raw_chem_name," "report_funcuse,raw_min_comp,raw_max_comp,unit_type," "ingredient_rank,raw_central_comp" "\n" "8,11177849.pdf,Alberto European Hairspray (Aerosol) - All Variants,,,aerosol hairspray," "0000075-37-6,hydrofluorocarbon 152a (difluoroethane),,0.39,0.42,1,," "\n" "8,11177849.pdf,A different prod_name with the same datadocument,,,aerosol hairspray," "0000064-17-5,sd alcohol 40-b (ethanol),,0.5,0.55,1,," ) sample_csv_bytes = csv_string.encode(encoding='UTF-8',errors='strict' ) in_mem_sample_csv = InMemoryUploadedFile( io.BytesIO(sample_csv_bytes), field_name='extract_file', name='British_Petroleum_(Air)_1_extract_template.csv', content_type='text/csv', size=len(csv_string), charset='utf-8') return in_mem_sample_csv
def convert(obj, file_format, size=None): extentions = {'jpeg2000': 'jp2', 'jpeg': 'jpg', 'webp': 'webp'} im = Image.open(obj.image).convert('RGB') # if format == 'jpeg' and image.mode == 'RGBA': # im = image.convert('RGB') # else: # im = image # create a BytesIO object im_io = BytesIO() # save image to BytesIO object if size: im = im.resize((size, size)) im.save(im_io, format=file_format) im_io.seek(0) # create a django-friendly Files object new_image = InMemoryUploadedFile( im_io, 'ImageField', add_extention(obj.image.name, extentions[file_format], size), 'image/%s' % extentions[file_format], sys.getsizeof(im_io), None) # new_image = InMemoryUploadedFile(im_io, name=(self.add_extention(self.image.name, extentions[format], size))) return new_image
def save(self, *args, **kwargs): image = self.image img = Image.open(image) min_height, min_width = Product.MIN_RESOLUTION max_height, max_width = Product.MAX_RESOLUTION if img.height < min_height or img.width < min_width: raise MinResolutionErrorExeption( 'Resolution of image less than minimum!') if img.height > max_height or img.width > max_width: new_img = img.convert('RGB') resized_new_img = new_img.resize(self.MIN_RESOLUTION, Image.ANTIALIAS) filestream = BytesIO() resized_new_img.save(filestream, 'JPEG', quality=90) filestream.seek(0) name = '{}.{}'.format(*self.image.name.split('.')) self.image = InMemoryUploadedFile(filestream, 'ImageField', name, 'jpeg/image', sys.getsizeof(filestream), None) super().save(*args, **kwargs) super().save(*args, **kwargs)
def save(self, skip_md=True, *args, **kwargs): if skip_md: self.mod_date = datetime.datetime.now() if self.image: im = Image.open(self.image) width, height = im.size output = BytesIO() n = 0.5 Width = floor(width * n) Height = floor(height * n) if width > 1000: im = im.resize((Width, Height)) im.save(output, format='JPEG', quality=100) output.seek(0) self.image = InMemoryUploadedFile( output, 'ImageField', "%s.jpg" % self.image.name.split('.')[0], 'image/jpeg', sys.getsizeof(output), None) super().save(*args, **kwargs) # Call the real save() method
def crop_image(image): from io import BytesIO pillow_image = Image.open(image) pillow_image = pillow_image.convert("RGB") width, height = pillow_image.size is_portrait = True if height > width else False temp = BytesIO() if is_portrait: coeff = int((height - width) / 2) cropped = pillow_image.crop((0, coeff, width, coeff + width)) elif width == height: return image else: coeff = int((width - height) / 2) cropped = pillow_image.crop((coeff, 0, coeff + height, height)) cropped.save(fp=temp, format="JPEG") return InMemoryUploadedFile(temp, None, "temp.jpg", "image/jpeg", temp.getbuffer().nbytes, None)
def change_image_resolution(image, min_resolution, max_resolution, max_image_size, new_image_width, new_image_height): img = Image.open(image) min_height, min_width = min_resolution max_height, max_width = max_resolution if image.size > max_image_size: raise Exception( f'Uploaded images\'s size could not be bigger than {max_image_size}' ) if img.height < min_height or img.width < min_width or img.height > max_height or img.width > max_width: new_img = img.convert('RGB') resized_new_image = new_img.resize((new_image_width, new_image_height), Image.ANTIALIAS) file_stream = BytesIO() resized_new_image.save(file_stream, 'JPEG', quality=90) file_stream.seek(0) name = image.name image = InMemoryUploadedFile(file_stream, 'ImageField', name, 'jpeg/image', sys.getsizeof(file_stream), None) return image
def compressImage(self, image): imageTemproary = PIL.Image.open(image).convert("RGB") outputIoStream = BytesIO() imageTemproary.thumbnail((900, 300), PIL.Image.ANTIALIAS) imageTemproary.save( outputIoStream, format="WEBP", quality=75, subsampling=0, optimize=True, ) outputIoStream.seek(0) image = InMemoryUploadedFile( outputIoStream, "image", "%s.webp" % image.name.split(".")[0], "image/webp", sys.getsizeof(outputIoStream), None, ) return image
def create_media(media): """Download media link""" if is_valid_url(media.data_value): filename = media.data_value.split('/')[-1] data_file = NamedTemporaryFile() content_type = mimetypes.guess_type(filename) with closing(requests.get(media.data_value, stream=True)) as r: for chunk in r.iter_content(chunk_size=CHUNK_SIZE): if chunk: data_file.write(chunk) data_file.seek(os.SEEK_SET, os.SEEK_END) size = os.path.getsize(data_file.name) data_file.seek(os.SEEK_SET) media.data_value = filename media.data_file = InMemoryUploadedFile( data_file, 'data_file', filename, content_type, size, charset=None) return media return None
def setUpForProtocol(self, protocol_class, repository): self.oaisource, _ = OaiSource.objects.get_or_create( identifier='deposit_oaisource', name='Repository OAI source', default_pubtype='preprint') logo = InMemoryUploadedFile(BytesIO(simple_png_image), None, 'logo.png', 'image/png', len(simple_png_image), None, None) self.repo = repository self.repo.oaisource = self.oaisource self.repo.logo = logo if not self.repo.description: self.repo.description = 'brsuatiercs' if not self.repo.name: self.repo.name = 'Test Repository' self.repo.protocol = protocol_class.__name__ self.repo.save() protocol_registry.register(protocol_class) self.proto = protocol_class(self.repo) self.form = None
def compress_image(img_file, max_dims=(1200, 1200), file_desc=''): """ Scales & compresses image. Scales an image file down if either dimension exceeds the maximum dimensions set. All images are converted/saved as a slightly compressed JPG. """ img = Image.open(img_file) if img.mode != 'RGB': img = img.convert('RGB') width, height = img.size max_width, max_height = max_dims # Create thumbnail with same aspect ratio if width > max_width or height > max_height: img.thumbnail(max_dims, Image.ANTIALIAS) output = BytesIO() img.save(output, format='JPEG', quality=55, optimize=True) output.seek(0) # Change stream position to byte 0 return InMemoryUploadedFile( output, 'ImageField', f'{img_file.name.split(".")[0]}{file_desc}.jpg', 'image/jpeg', sys.getsizeof(output), None)
def save(self, *args, **kwargs): im = Image.open(self.image) im.load() rbg_img = im.convert('RGB') rbg_img.load() im_io = BytesIO() rbg_img.save(im_io, 'JPEG', quality=75) self.image = InMemoryUploadedFile( im_io, 'ImageField', "%s.jpg" % self.image.name.split('.')[0], 'image/jpeg', im_io.getbuffer().nbytes, None) if self.pk: self.is_disabled = should_be_disabled(self) '''try: icon,im_io = JPEGSaveWithTargetSize(self.image,"%s_icon.jpg" % self.image.name,3000) self.icon = InMemoryUploadedFile(im_io, 'ImageField', "%s_icon.jpg" % self.image.name.split('.')[0], 'image/jpeg', im_io.getbuffer().nbytes, None) except Exception as e: # File too big to be compressed to 3kb pass''' super().save(*args, **kwargs)
def save(self, *args, **kwargs): image = self.image img = Image.open(image) min_height, min_width = self.MIN_RESOLUTION max_height, max_width = self.MAX_RESOLUTION if img.height < min_height or img.width < min_width: raise MinResolutionErrorException('Разрешение изображение меньше минимального!') if img.height > max_height or img.width > max_width: raise MaxResolutionErrorException('Разрешение изображение больше максимального!') image = self.image img = Image.open(image) new_img = img.convert('RGB') resized_new_img = new_img.resize((2000, 2000), Image.ANTIALIAS) filestream = BytesIO() resized_new_img.save(filestream, 'JPEG', quality=90) filestream.seek(0) name = '{}.{}'.format(*self.image.name.split('.')) self.image = InMemoryUploadedFile( filestream, 'ImageField', name, 'jpeg/image', sys.getsizeof(filestream), None ) super().save(*args, **kwargs)
def file(self): if self._file: self._file.seek(0) return self._file BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) file_path = os.path.join(BASE_DIR, "excel_import/testdata/test.xlsx") f = open(file_path, 'rb') io = BytesIO(f.read()) f.seek(0, os.SEEK_END) size = f.tell() f.close() file = InMemoryUploadedFile( io, None, 'test.xlsx', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', size, None) file.seek(0) self._file = file return file
def save_and_cleanup(image, instance=None): """Save and close the file""" if not isinstance(instance, (models.Book, models.User, models.SiteSettings)): return False file_name = "%s-%s.jpg" % (str(instance.id), str(uuid4())) image_buffer = BytesIO() try: try: old_path = instance.preview_image.path except ValueError: old_path = "" # Save image.save(image_buffer, format="jpeg", quality=75) instance.preview_image = InMemoryUploadedFile( ContentFile(image_buffer.getvalue()), "preview_image", file_name, "image/jpg", image_buffer.tell(), None, ) save_without_broadcast = isinstance(instance, (models.Book, models.User)) if save_without_broadcast: instance.save(broadcast=False) else: instance.save() # Clean up old file after saving if os.path.exists(old_path): os.remove(old_path) finally: image_buffer.close() return True
def add_movie(index, movie_title, genres, rating, intrating, ia): IMAGE_WIDTH = 182 IMAGE_HEIGHT = 268 try: movie = ia.search_movie(movie_title)[0] sr_title = movie['title'][:25] ln_title = movie['long imdb title'] title = movie['title'] yr = str(movie['year']) half_rating = True if rating > intrating else False movie_obj = Movie(title=title, short_title=sr_title, long_title=ln_title, year=yr, ratings=intrating, half_rating=half_rating, top_movie=False, genres=genres) img_field = movie_obj.image print(str(index) + " : " + movie['title']) resp = requests.get(movie['full-size cover url']) pillow_image = Image.open(BytesIO(resp.content)) img_name = str(movie['title']) + ".jpg" img = resize_image(pillow_image, width=IMAGE_WIDTH, height=IMAGE_HEIGHT) img_field.save( img_name, InMemoryUploadedFile(img, None, img_name, 'image/jpeg', img.tell, None)) movie_obj.save() except IndexError as ie_error: print("Index Error: " + str(ie_error) + " : " + movie_title) except: print("Exception occured in movie: " + movie_title)
def save(self, *args, **kwargs): if not self.id: log(user=self.user, action='CREATE_PROFILE', extra={ 'user_name': self.user.username }) else: log(user=self.user, action='UPDATE_PROFILE', extra={ 'user_name': self.user.username }) self.photo_height_field = 400 self.photo_width_field = 400 # image compression and conversion to JPG if not self.user_photo == 'None/No_image.png': try: img = Image.open(BytesIO(self.user_photo.read())) if img.mode != 'RGB': img = img.convert('RGB') img.thumbnail((self.user_photo.width / 1.5, self.user_photo.height / 1.5), Image.ANTIALIAS) output = BytesIO() img.save(output, format='JPEG', quality=70) output.seek(0) self.user_photo = InMemoryUploadedFile(output, 'ImageField', "%s.jpg" % self.user_photo.name.split('.')[0], 'image/jpeg', None, None) log(user=self.user, action='PHOTO_UPDATE', extra={ 'user_name': self.user.username, 'user_photo': self.user_photo.url, }) except ValueError: log(user=self.user, action='IMAGE_VALUE_ERROR', extra={ 'user_name': self.user.username, 'user_photo': self.user_photo.url, }) super(UserProfile, self).save(*args, **kwargs)
def update(request): if request.method == 'POST': author_info = AuthorInfo.objects.get(user=request.user) d = { 'success': False, 'message': '', } t = request.POST.get('type', '') if t == 'thumbnail': image = request.FILES.get('image', '') try: io = StringIO() for chunk in image.chunks(): io.write(chunk) io.seek(0) im = PIL_Image.open(io) im.thumbnail((64, 64), PIL_Image.ANTIALIAS) tmp = oStringIO.StringIO() im.save(tmp, 'JPEG') tmp_file = InMemoryUploadedFile(tmp, None, 'foo.jpg', 'image/jpeg', tmp.len, None) author_info.profile_image = tmp_file author_info.save() except Exception, e: d['message'] = str(e) else: d['success'] = True d['message'] = author_info.profile_image.url elif t == 'description': val = request.POST.get('value', '') try: author_info.introduce_simple = val author_info.save() except Exception, e: d['message'] = str(e) else: d['success'] = True
def post(self, request, *args, **kwargs): print(request.POST) form = self.form_class(data=request.POST, ) if not form.is_valid(): failed_dict = form.errors return HttpResponseBadRequest( content=list(failed_dict.values())[0][0]) if request.POST.get( "image") and request.POST.get("image") != IMAGE_DEFAULT: try: image = base64.b64decode( request.POST.get("image").split(';base64,')[1]) except Exception: return HttpResponseBadRequest(content="图片格式有问题!!") s = imghdr.what(None, image) print(s) f = BytesIO() f.write(image) image = InMemoryUploadedFile(f, "test", 'png', None, len(image), None, None) else: image = None print(image) try: user_catalog = UserCatagory.objects.create( author=request.user, name=request.POST.get("name"), describe=request.POST.get("describe"), image=image) except IntegrityError: return HttpResponseBadRequest(content="该标签你已经使用!!") response_data = { "err_msg": None, "status": "completed", "name": user_catalog.name, "id": user_catalog.id } return JsonResponse(data=response_data)
def test_post_submission_require_auth_other_user(self): self.user.profile.require_auth = True self.user.profile.save() alice_data = { 'username': '******', 'password1': 'alicealice', 'password2': 'alicealice', 'email': '*****@*****.**', } self._create_user_profile(alice_data) count = Attachment.objects.count() s = self.surveys[0] media_file = "1335783522563.jpg" path = os.path.join(self.main_directory, 'fixtures', 'transportation', 'instances', s, media_file) with open(path, 'rb') as f: f = InMemoryUploadedFile(f, 'media_file', media_file, 'image/jpg', os.path.getsize(path), None) submission_path = os.path.join( self.main_directory, 'fixtures', 'transportation', 'instances', s, s + '.xml') with open(submission_path) as sf: data = {'xml_submission_file': sf, 'media_file': f} request = self.factory.post('/submission', data) response = self.view(request) self.assertEqual(response.status_code, 401) response = self.view(request, username=self.user.username) self.assertEqual(response.status_code, 401) self.assertEqual(count, Attachment.objects.count()) # rewind the file and redo the request since they were # consumed sf.seek(0) request = self.factory.post('/submission', data) auth = DigestAuth('alice', 'alicealice') request.META.update(auth(request.META, response)) response = self.view(request, username=self.user.username) self.assertContains(response, 'Forbidden', status_code=403)
def populate_feat_directory(request,collection,existing_dir=None): from nidmfsl.fsl_exporter.fsl_exporter import FSLtoNIDMExporter tmp_dir = tempfile.mkdtemp() if existing_dir is None else existing_dir exc = ValidationError try: if existing_dir is None: zip = zipfile.ZipFile(request.FILES['file']) zip.extractall(path=tmp_dir) rootpaths = [v for v in os.listdir(tmp_dir) if not v.startswith('.') and not v.startswith('__MACOSX')] if not rootpaths: raise exc("No contents found in the FEAT directory.") subdir = os.path.join(tmp_dir,rootpaths[0]) feat_dir = subdir if len(rootpaths) is 1 and os.path.isdir(subdir) else tmp_dir except: raise exc("Unable to unzip the FEAT directory: \n{0}.".format(get_traceback())) try: fslnidm = FSLtoNIDMExporter(feat_dir=feat_dir, version="1.2.0") fslnidm.parse() nidm_file = fslnidm.export() except: raise exc("Unable to parse the FEAT directory: \n{0}.".format(get_traceback())) if not os.path.exists(nidm_file): raise exc("Unable find nidm export of FEAT directory.") try: fh = open(nidm_file,'r') request.FILES['file'] = InMemoryUploadedFile( ContentFile(fh.read()), "file", fh.name.split('/')[-1], "application/zip", os.path.getsize(nidm_file), "utf-8") except: raise exc("Unable to convert NIDM results for NeuroVault: \n{0}".format(get_traceback())) else: return populate_nidm_results(request,collection) finally: shutil.rmtree(tmp_dir)
def image_resize(self, image_title, width, height): """Function to resize the images for smaller memory.""" # Checks if the instance already exists this_object = None image_field = getattr(self, image_title) try: # If it exists, selects current image, if not goes to next step this_object = self.__class__.objects.get(pk=self.id) object_image = getattr(this_object, image_title) except self.__class__.DoesNotExist: pass try: img = Image.open(image_field) i_format = img.format.lower() # Prevents images from being copied on every save # will save a new copy on an upload if (this_object and f'{image_field.name}'.replace(' ', '_').replace( '(', '').replace(')', '') not in object_image.name) or (not this_object): # Image is resized output_size = (width, height) img = img.resize(size=(output_size)) # Converts format while in memory output = BytesIO() img.save(output, format=i_format) output.seek(0) # Replaces the Imagefield value with the newly converted image image_field = InMemoryUploadedFile( output, 'ImageField', f'{image_field.name.split(".")[0]}_{random_str(8)}.{i_format}', 'image/jpeg', sys.getsizeof(output), None) return image_field # if the image doesn't need to be changed, returns false return False # If uploading multiple images on a new file there can this error. except ValueError: return False
def test_register_records_header(self): ds_pk = DataSource.objects.first().pk csv_string = ("filename,title,document_type,product,url,organization\n" "1.pdf,Home Depot,2,,www.homedepot.com/594.pdf,\n" "2.pdf,Home Depot,2,,www.homedepot.com/fb5.pdf,\n") csv_string_bytes = csv_string.encode(encoding="UTF-8", errors="strict") in_mem_sample_csv = InMemoryUploadedFile( io.BytesIO(csv_string_bytes), field_name="register_records", name="register_records.csv", content_type="text/csv", size=len(csv_string), charset="utf-8", ) data = { "name": "Slinky", "group_type": 1, "downloaded_by": 1, "downloaded_at": timezone.now(), "download_script": 1, "data_source": ds_pk, "csv": in_mem_sample_csv, } request = self.factory.post(path=f"/datasource/{ds_pk}/datagroup_new/", data=data) middleware = SessionMiddleware() middleware.process_request(request) request.session.save() middleware = MessageMiddleware() middleware.process_request(request) request.session.save() request.user = User.objects.get(username="******") resp = data_group_create(request=request, pk=6) self.assertContains( resp, "CSV column titles should be ['filename', 'title'," " 'document_type', 'url', 'organization']", )
def test_attachment_file_name_validation(self): """ Test that a clear exception is raised when an attachement is received whose file name exceeds 100 chars """ md = """ | survey | | | | | | type | name | label | | | image | image1 | Photo | | | image | image2 | Photo | """ self._create_user_and_login() self.xform = self._publish_markdown(md, self.user) xml_string = """ <data id="{}"> <meta> <instanceID>uuid:UJ5jSMAJ1Jz4EszdgHy8n851AsKaqBPO5</instanceID> </meta> <image1>1300221157303.jpg</image1> <image2>1300375832136.jpg</image2> </data> """.format(self.xform.id_string) file_path = "{}/apps/logger/tests/Health_2011_03_13."\ "xml_2011-03-15_20-30-28/1300221157303"\ ".jpg".format(settings.PROJECT_ROOT) f = open(file_path, 'rb') media_file = InMemoryUploadedFile( file=f, field_name="image1", name=f'{f.name} +\ test_file_name_test_file_name_test_file_name_test_file_name_test_file_name_test_file_name', # noqa content_type="image/jpeg", size=os.path.getsize(file_path), charset=None) with self.assertRaises(AttachmentNameError): create_instance(self.user.username, BytesIO(xml_string.strip().encode('utf-8')), media_files=[media_file])
def _update_image(profile, image_url): ''' Updates the user profile's image to the given image url Unfortunately this is quite a pain to get right with Django Suggestions to improve this are welcome ''' image_name = 'fb_image_%s.jpg' % profile.facebook_id image_temp = NamedTemporaryFile() image_response = urllib2.urlopen(image_url) image_content = image_response.read() image_temp.write(image_content) http_message = image_response.info() image_size = len(image_content) content_type = http_message.type image_file = InMemoryUploadedFile( file=image_temp, name=image_name, field_name='image', content_type=content_type, size=image_size, charset=None ) profile.image.save(image_name, image_file) image_temp.flush() profile_dirty = True return profile_dirty
def create_canary_file(cls, user, type='all'): if not user: user = UserHelpers.create_authenticated_user() fd = open('canary_utils/tests/excel.xlsx', 'rb') size = len(fd.read()) fd.seek(0) canary = InMemoryUploadedFile(fd, 'uploaded', 'excel.xlsx', content_type='application/octet-stream', size=size, charset='binary') canary_item = CanaryItem.create_canary(user, canary, type, 'test_unit', True, 'http', 'test.legit.subdomain.example') fd.close() return canary_item
def get_test_image(size=None, format_image='PNG'): """ Returns an image for running tests """ io_var = BytesIO() color = (255, 0, 0, 0) if size is None: size = (10, 10) image = Image.new('RGBA', size, color) image.save(io_var, format=format_image) image_file = InMemoryUploadedFile( io_var, None, 'test.{}'.format(format_image.lower()), format_image.lower(), None, None, ) image_file.seek(0) return image_file
def _create_gif_filestream_from_base64(self, str_base64, **kwargs): """ Helper function to create filestream for upload. Parameters : strData : str, test string data Optional Arguments : filename : str, Defaults to 'test.txt' """ filename = kwargs.get('filename', 'test.gif') data = base64.b64decode(str_base64) filedata = BytesIO(data) filestream = InMemoryUploadedFile( filedata, None, filename, 'image', len(data), None ) return filestream
def test_post_submission_require_auth_anonymous_user(self): self.user.profile.require_auth = True self.user.profile.save() count = Attachment.objects.count() s = self.surveys[0] media_file = "1335783522563.jpg" path = os.path.join(self.main_directory, 'fixtures', 'transportation', 'instances', s, media_file) with open(path) as f: f = InMemoryUploadedFile(f, 'media_file', media_file, 'image/jpg', os.path.getsize(path), None) submission_path = os.path.join(self.main_directory, 'fixtures', 'transportation', 'instances', s, s + '.xml') with open(submission_path) as sf: data = {'xml_submission_file': sf, 'media_file': f} request = self.factory.post('/submission', data) response = self.view(request) self.assertEqual(response.status_code, 401) response = self.view(request, username=self.user.username) self.assertEqual(response.status_code, 401) self.assertEqual(count, Attachment.objects.count())
def save(self): if not self.image_origin: super(Category, self).save() elif str(self.image_origin) == str( Category.objects.get(pk=self.id).image_origin): super(Category, self).save() elif self.image_origin and FORCE_RESIZE_IMAGE: # try: # unused_image=Category.objects.get(pk=self.id).image # if unused_image is not None: # input(unused_image) # #unused_image= Image.open(unused_image) # input(unused_image.name) # os.remove(unused_image.name) # except: # pass #Opening the uploaded image image = Image.open(self.image_origin) output = BytesIO() #Resize/modify the image image = image.resize((CATEGORY_IMAGE_WIDTH, CATEGORY_IMAGE_HEIGHT), Image.ANTIALIAS) #after modifications, save it to the output image.save(output, format='JPEG', quality=95) output.seek(0) #change the imagefield value to be the newley modifed image value self.image_origin = InMemoryUploadedFile( output, 'ImageField', "%s.jpg" % self.image_origin.name.split('.')[0], IMAGE_FOLDER + 'Category/image/jpeg', sys.getsizeof(output), None) super(Category, self).save()
def resize_image(image: InMemoryUploadedFile, max: int, quality=85) -> InMemoryUploadedFile: """ Returns a resized image based on the given maximum size """ with Image.open(image) as img: width, height = img.size # no need to resize if width or height is already less than the max if width <= max or height <= max: return image if width > height: width_ratio = max / float(width) new_height = int((float(height) * float(width_ratio))) img = img.resize((max, new_height), Image.ANTIALIAS) else: height_ratio = max / float(height) new_width = int((float(width) * float(height_ratio))) img = img.resize((new_width, max), Image.ANTIALIAS) with BytesIO() as buffer: img.save(fp=buffer, format="PNG", quality=quality) resized_image = ContentFile(buffer.getvalue()) file_name_without_ext = os.path.splitext(image.name)[0] return InMemoryUploadedFile( resized_image, "ImageField", "%s.png" % file_name_without_ext, "image/png", resized_image.tell(), None )