def fetch_image_to_image_field(image_url: str, target_field: ImageField) -> None: """Fetches image from url and assigns it to image file field""" response = requests.get(image_url) response.raise_for_status() content = response.content content_file = ContentFile(content) content_type = response.headers.get('content-type') extension = guess_extension(content_type) target_file_name = '{0}{1}'.format(uuid4(), extension) target_field.save( default_storage.get_available_name(target_file_name), content_file )
def resize(self, imageField: models.ImageField, t_height, t_width): height = imageField.height width = imageField.width print (r"Max H {}, Max W {}, Image H {}, Image W {}".format (t_height, t_width, height, width)) if width != t_width or height != t_height: print ("===============> Resizing Image") imageField.open() im = Image.open(imageField) # Catch original im.load() source_image = im.convert('RGB') source_image = source_image.resize((t_width, t_height), Image.ANTIALIAS) # Resize to size output = BytesIO() source_image.save(output, format='JPEG') # Save resize image to bytes output.seek(0) content_file = ContentFile(output.read()) # Read output and create ContentFile in memory file = File(content_file) random_name = f'{uuid.uuid4()}.jpg' imageField.save(random_name, file, save=False)
def _make_thumbnail(self, field: ImageField): thumbnail = make_thumbnail(field) field.save(field.name, thumbnail, save=False)