def test_closing_of_filenames(self): """ get_image_dimensions() called with a filename should closed the file. """ # We need to inject a modified open() builtin into the images module # that checks if the file was closed properly if the function is # called with a filename instead of an file object. # get_image_dimensions will call our catching_open instead of the # regular builtin one. class FileWrapper(object): _closed = [] def __init__(self, f): self.f = f def __getattr__(self, name): return getattr(self.f, name) def close(self): self._closed.append(True) self.f.close() def catching_open(*args): return FileWrapper(open(*args)) from django.core.files import images images.open = catching_open try: get_image_dimensions(os.path.join(os.path.dirname(__file__), "test1.png")) finally: del images.open self.assertTrue(FileWrapper._closed)
def save(self, force_insert=False, force_update=False, **kwargs): """Overrides models.Model.save. - Generates slug. - Saves image file. """ # prefill the slug with the ID, it requires double save if not self.id: if isinstance(self.image, UploadedFile): # due to PIL has read several bytes from image, position in file has to be reset self.image.seek(0) super(Photo, self).save(force_insert, force_update) self.width, self.height = get_image_dimensions(self.image.path) self.slug = str(self.id) + '-' + self.slug force_insert, force_update = False, True image_changed = False else: old = Photo.objects.get(pk = self.pk) image_changed = old.image != self.image # rename image by slug imageType = detect_img_type(self.image.path) if imageType is not None: self.image = file_rename(self.image.name, self.slug, PHOTOS_TYPE_EXTENSION[ imageType ]) # delete formatedphotos if new image was uploaded if image_changed: super(Photo, self).save(force_insert=force_insert, force_update=force_update, **kwargs) self.width, self.height = get_image_dimensions(self.image.path) force_insert, force_update = False, True for f_photo in self.formatedphoto_set.all(): f_photo.delete() super(Photo, self).save(force_insert=force_insert, force_update=force_update, **kwargs)
def test_not_closing_of_files(self): """ Open files passed into get_image_dimensions() should stay opened. """ empty_io = StringIO() try: get_image_dimensions(empty_io) finally: self.assertTrue(not empty_io.closed)
def test_width(self, image): ''' Make sure that if width shrinks, then height shrinks proportionally ''' transformed_size = 10 transform = simpleimages.transforms.Scale(width=transformed_size) new_image = transform(image.django_file) new_height, new_width = get_image_dimensions(new_image) assert get_image_dimensions(new_image) == (transformed_size,) * 2
def test_over_large(self, image): ''' if specified dimension is larger than image, it shouldn't enlarge the image ''' transformed_size = 200 transform = simpleimages.transforms.Scale(width=transformed_size) new_image = transform(image.django_file) new_height, new_width = get_image_dimensions(new_image) assert get_image_dimensions(new_image) == image.dimensions
def test_multiple_calls(self): """ Multiple calls of get_image_dimensions() should return the same size. """ from django.core.files.images import ImageFile img_path = os.path.join(os.path.dirname(__file__), "test.png") image = ImageFile(open(img_path)) image_pil = Image.open(img_path) size_1, size_2 = get_image_dimensions(image), get_image_dimensions(image) self.assertEqual(image_pil.size, size_1) self.assertEqual(size_1, size_2)
def test_multiple_calls(self): """ Multiple calls of get_image_dimensions() should return the same size. """ img_path = os.path.join(os.path.dirname(upath(__file__)), "test.png") with open(img_path, 'rb') as fh: image = images.ImageFile(fh) image_pil = Image.open(fh) size_1 = images.get_image_dimensions(image) size_2 = images.get_image_dimensions(image) self.assertEqual(image_pil.size, size_1) self.assertEqual(size_1, size_2)
def test_width_and_height(self, image): ''' Make sure that if both are set, will shrink to max of either ''' transform = simpleimages.transforms.Scale(width=10, height=10) image.dimensions = (100, 10) new_image = transform(image.django_file) assert get_image_dimensions(new_image)[0] == 10 image.dimensions = (10, 100) new_image = transform(image.django_file) assert get_image_dimensions(new_image)[1] == 10
def save(self, *args, **kwargs): if self.thumbnail: from django.core.files.images import get_image_dimensions import django if django.VERSION[1] < 2: width, height = get_image_dimensions(self.thumbnail.file) else: width, height = get_image_dimensions(self.thumbnail.file, close=True) else: width, height = None, None self.thumbnail_width = width self.thumbnail_height = height super(Category, self).save(*args, **kwargs)
def clean_cover(self): cover = self.cleaned_data['cover'] if cover: if not cover.name: if cover.content_type not in settings.IMAGE_CONTENT_TYPE: raise forms.ValidationError( _(u"Journal cover image extension is not allowed! Please select another file.")) if cover.size > settings.JOURNAL_COVER_MAX_SIZE: raise forms.ValidationError( _(u"Journal cover image file size is too large! Please select another file.")) w, h = get_image_dimensions(cover) if w != settings.IMAGE_DIMENSIONS['width_cover']: raise forms.ValidationError( _(u"The image is {image_size}px pixel wide. It's supposed to be {expected_size}px".format( image_size=w, expected_size=settings.IMAGE_DIMENSIONS['width_cover']))) if h != settings.IMAGE_DIMENSIONS['height_cover']: raise forms.ValidationError( _("The image is {image_size}px pixel high. It's supposed to be {expected_size}px".format( image_size=h, expected_size=settings.IMAGE_DIMENSIONS['height_cover']))) return cover
def database_get_image_dimensions(file, close=False, dimensions=None): """ Returns the (width, height) of an image, given ThumbnailFile. Set 'close' to True to close the file at the end if it is initially in an open state. Will attempt to get the dimensions from the file itself if they aren't in the db. """ storage_hash = utils.get_storage_hash(file.storage) dimensions = None dimensions_cache = None try: thumbnail = models.Thumbnail.objects.select_related('dimensions').get( storage_hash=storage_hash, name=file.name) except models.Thumbnail.DoesNotExist: thumbnail = None else: try: dimensions_cache = thumbnail.dimensions except models.ThumbnailDimensions.DoesNotExist: dimensions_cache = None if dimensions_cache: return dimensions_cache.width, dimensions_cache.height dimensions = get_image_dimensions(file, close=close) if settings.THUMBNAIL_CACHE_DIMENSIONS and thumbnail: dimensions_cache = models.ThumbnailDimensions(thumbnail=thumbnail) dimensions_cache.width, dimensions_cache.height = dimensions dimensions_cache.save() return dimensions
def save(self, *args, **kwargs): mug, x, y, size = [self.cleaned_data[key] for key in ('mug', 'x', 'y', 'size')] mug = mug or self.instance.mug if get_image_dimensions(mug) != (100,100): if all([x, y, size]): make_thumb(mug, (x, y), size) return super(PostForm, self).save(*args, **kwargs)
def clean_avatar(self): avatar = self.cleaned_data["profile_picture"] try: w, h = get_image_dimensions(avatar) # validate dimensions max_width = max_height = 100 if w > max_width or h > max_height: raise forms.ValidationError( u"Please use an image that is " "%s x %s pixels or smaller." % (max_width, max_height) ) # validate content type main, sub = avatar.content_type.split("/") if not (main == "image" and sub in ["jpeg", "pjpeg", "gif", "png"]): raise forms.ValidationError(u"Please use a JPEG, " "GIF or PNG image.") # validate file size if len(avatar) > (20 * 1024): raise forms.ValidationError(u"Avatar file size may not exceed 20k.") except AttributeError: """ Handles case when we are updating the user profile and do not supply a new avatar """ pass return avatar
def clean_avatar(self): avatar = self.cleaned_data['avatar'] try: w, h = get_image_dimensions(avatar) #validate dimensions max_width = max_height = 100 if w > max_width or h > max_height: raise forms.ValidationError( u'Please use an image that is ' '%s x %s pixels or smaller.' % (max_width, max_height)) #validate content type main, sub = avatar.content_type.split('/') if not (main == 'image' and sub in ['jpeg', 'pjpeg', 'gif', 'png']): raise forms.ValidationError(u'Please use a JPEG, ' 'GIF or PNG image.') #validate file size if len(avatar) > (20 * 1024): raise forms.ValidationError( u'Avatar file size may not exceed 20k.') except AttributeError: """ Handles case when we are updating the user profile and do not supply a new avatar """ pass return avatar
def clean_picture(self): picture = self.cleaned_data['picture'] try: w, h = get_image_dimensions(picture) #validate dimensions max_width = max_height = 4000 if w > max_width or h > max_height: raise forms.ValidationError( u'Please use an image that is ' '%s x %s pixels or smaller.' % (max_width, max_height)) #validate content type main, sub = picture.content_type.split('/') if not (main == 'image' and sub in ['jpeg', 'pjpeg', 'gif', 'png']): raise forms.ValidationError(u'Please use a JPEG, ' 'GIF or PNG image.') #validate file size image = self.cleaned_data.get('image',False) if image: if image._size > 6*1024*1024: raise ValidationError("Image file too large ( > 6mb )") return image except AttributeError: pass except TypeError: return picture return picture
def __set__(self, instance, value): super(ImageFileDescriptor, self).__set__(instance, value) # The rest of this method deals with width/height fields, so we can # bail early if neither is used. if not self.field.width_field and not self.field.height_field: return # We need to call the descriptor's __get__ to coerce this assigned # value into an instance of the right type (an ImageFieldFile, in this # case). value = self.__get__(instance) if not value: return # Get the image dimensions, making sure to leave the file in the same # state (opened or closed) that we got it in. However, we *don't* rewind # the file pointer if the file is already open. This is in keeping with # most Python standard library file operations that leave it up to the # user code to reset file pointers after operations that move it. from django.core.files.images import get_image_dimensions close = value.closed value.open() try: width, height = get_image_dimensions(value) finally: if close: value.close() # Update the width and height fields if self.field.width_field: setattr(value.instance, self.field.width_field, width) if self.field.height_field: setattr(value.instance, self.field.height_field, height)
def clean(self): data = self.cleaned_data if data.get("scheduled_datetime"): sched_dt = data["scheduled_datetime"] sched_tz = timezone.pytz.timezone(data.get("scheduled_tz")) sched_dt = sched_tz.localize(sched_dt.replace(tzinfo=None)) data["scheduled_datetime"] = timezone.localtime(sched_dt) if data.get("attached_media") and data.get("media_url"): raise forms.ValidationError(_("Only one of media URL or " "attached media may be provided")) if data.get("media_url"): response = requests.get(data["media_url"]) if not response.ok: raise forms.ValidationError(_("An error occurred while " "downloading the media from the URL")) ext = mimetypes.guess_extension(response.headers['content-type']) ff = tempfile.NamedTemporaryFile(suffix=ext) ff.write(response.content) img_file = ImageFile(ff, name=ff.name) height, width = get_image_dimensions(img_file) if height is None or width is None: ff.close() raise forms.ValidationError(_("Invalid image")) data["attached_media"] = img_file return data
def clean_image(self): image = self.cleaned_data['image'] width, height = get_image_dimensions(image) if width != SIDE_AD_IMG_WIDTH or height != SIDE_AD_IMG_HEIGHT: raise ValidationError(_(u'Image must have {0}x{1} px size.'.format(SIDE_AD_IMG_WIDTH, SIDE_AD_IMG_HEIGHT))) return image
def clean_button(self): button = self.cleaned_data.get('button') if button: width, height = get_image_dimensions(button) if width != 11 or height != 11: raise ValidationError("width or height is not 11, (11x11)") return button
def clean_profile_image(self): profile_image = self.cleaned_data['profile_image'] try: w, h = get_image_dimensions(profile_image) #validate dimensions max_height = 960 max_width = 1280 if w > max_width or h > max_height: raise forms.ValidationError(u'Please use an image that is {w} x {h} pixels or smaller.'.format(w=max_width, h=max_height)) #validate content type main, sub = profile_image.content_type.split('/') if not (main == 'image' and sub in ['jpg', 'jpeg', 'pjpeg', 'png']): raise forms.ValidationError(u'Please use a JPEG or PNG image.') #validate file size if len(profile_image) > (2000 * 1024): raise forms.ValidationError('Profile image file size may not exceed 2MB.') except AttributeError: pass return profile_image
def test_create_issuer_image_500x300_resizes_to_400x400(self): view = IssuerList.as_view() with open(os.path.join(os.path.dirname(__file__), 'testfiles', '500x300.png'), 'r') as badge_image: issuer_fields_with_image = { 'name': 'Awesome Issuer', 'description': 'An issuer of awe-inspiring credentials', 'url': 'http://example.com', 'email': '*****@*****.**', 'image': badge_image, } request = factory.post('/v1/issuer/issuers', issuer_fields_with_image, format='multipart') force_authenticate(request, user=get_user_model().objects.get(pk=1)) response = view(request) self.assertEqual(response.status_code, 201) badge_object = response.data.get('json') derived_slug = badge_object['id'].split('/')[-1] new_issuer = Issuer.objects.get(slug=derived_slug) image_width, image_height = \ get_image_dimensions(new_issuer.image.file) self.assertEqual(image_width, 400) self.assertEqual(image_height, 400)
def clean(self, *args, **kwargs): from django.core.files.images import get_image_dimensions data = super(ExtendedImageField, self).clean(*args, **kwargs) image = data.file # Controls the file size if self.max_upload_size and hasattr(image, 'size'): if image.size > self.max_upload_size: raise ValidationError( _('Files of size greater than {} are not allowed. Your file is {}').format( filesizeformat(self.max_upload_size), filesizeformat(image.size) ) ) # Controls the image size image_width, image_height = get_image_dimensions(data) if (self.min_width and self.max_width and not self.min_width <= image_width <= self.max_width): raise ValidationError( _('Images of width lesser than {}px or greater than {}px or are not allowed. The width of your image is {}px').format( self.min_width, self.max_width, image_width)) if self.min_height and self.max_height and not self.min_height <= image_height <= self.max_height: raise ValidationError( _('Images of height lesser than {}px or greater than {}px or are not allowed. The height of your image is {}px').format( self.min_height, self.max_height, image_height)) return data
def clean_thumbnail(self): thumbnail = self.cleaned_data.get("thumbnail") if thumbnail: w, h = get_image_dimensions(thumbnail) if w < Course.THUMBNAIL_WIDTH or h < Course.THUMBNAIL_HEIGHT: raise forms.ValidationError(self.error_messages['invalid_image']) return thumbnail
def get_image_data_scaled(image_data, width): # NOTE: We refuse to scale images if we do not # have the Python Imaging Library. if not mysite.base.depends.Image: logger.info( "NOTE: We cannot resize this image, so we are going to pass it through. See ADVANCED_INSTALLATION.mkd for information on PIL.") return image_data # scale it image_fd = StringIO.StringIO(image_data) im = mysite.base.depends.Image.open(image_fd) image_fd.seek(0) w, h = get_image_dimensions(image_fd) new_w = int(width) new_h = int((h * 1.0 / w) * width) smaller = im.resize((new_w, new_h), mysite.base.depends.Image.ANTIALIAS) # "Save" it to memory new_image_fd = StringIO.StringIO() smaller.save(new_image_fd, format='PNG') new_image_fd.seek(0) # pull data out image_data = new_image_fd.getvalue() return image_data
def clean_avatar(self): avatar = self.cleaned_data['avatar'] try: w, h = get_image_dimensions(avatar) #validate dimensions max_width = max_height = 2800 if w > max_width or h > max_height: raise forms.ValidationError( u'Please use an image that is ' '%(width)s x %(height)s pixels or smaller.', params={'width': max_width, 'height': max_height}, code='invalid') #validate content type main, sub = avatar.content_type.split('/') if not (main == 'image' and sub in ['jpeg', 'pjpeg', 'gif', 'png']): raise forms.ValidationError(u'Please use a JPEG, ' 'GIF or PNG image.', code='invalid') #validate file size if len(avatar) > (200 * 1024): raise forms.ValidationError( u'Avatar file size may not exceed 200k.', code='invalid') except AttributeError: pass except TypeError: pass return avatar
def file_type(self): t = self.filetypes_dict[self.type] if self.type == 'image': from django.core.files.images import get_image_dimensions d = get_image_dimensions(self.file.file) if d: t += "<br/>%d×%d" % ( d[0], d[1] ) return t
def clean_photo(self): # Safe copy of data... self.cleaned_data['photo'].seek(0) data = self.cleaned_data['photo'].read() self.cleaned_data['photo'].seek(0) data_fd = StringIO.StringIO(data) w, h = get_image_dimensions(data_fd) if w > 200: # Scale it down. too_big = PIL.Image.open(StringIO.StringIO(data)) format = too_big.format new_w = 200 new_h = (h * 1.0 / w) * 200 smaller = too_big.resize((new_w, new_h), PIL.Image.ANTIALIAS) # "Save" it to memory new_image_fd = StringIO.StringIO() smaller.save(new_image_fd, format=format) new_image_fd.seek(0) old = self.cleaned_data['photo'] new_image_uploaded_file = InMemoryUploadedFile( new_image_fd, '', old.name, old.content_type, new_image_fd.len, old.charset) # Modify the self.cleaned_data[] self.cleaned_data['photo'] = new_image_uploaded_file return self.cleaned_data['photo']
def clean_answer(self): answer = self.cleaned_data['answer'] if answer and not get_image_dimensions(answer.file): raise ValidationError(_( "We couldn't read your file. Make sure it's a .jpeg, .png, or " ".gif file, not a .psd or other unsupported type.")) return answer
def post(self, request, username): """Handles upload of profile picture by user.""" if not is_user_current_user(request, username): self.error = 'You are not permitted to do this.' self.status = 405 return render(request, 'error.html', { 'error': self.error }, status=self.status) else: user = User.objects.get(username=username) p = user.profile form = ProfilePictureUploadForm(request.POST, request.FILES) if form.is_valid(): try: image = request.FILES['image'] w, h = get_image_dimensions(image) if w < 200 or h < 200 or w > 1000 or h > 1000: error = """Image dimension should be between 200x200 and 1000x1000""" raise if p.picture: os.remove(p.picture.path) p.picture = image p.save() print(p.picture.path) returnpath = '/user/' + \ user.username + '/crop_profilepicture' return HttpResponseRedirect(returnpath) except: return render(request, 'uploadprofilepicture.html', {'user': user, 'error': error}) else: return render(request, 'uploadprofilepicture.html', {'user': user})
def test_badgeclass_put_image_multipart(self): test_user = self.setup_user(authenticate=True) test_issuer = self.setup_issuer(owner=test_user) badgeclass_props = { 'name': 'Badge of Awesome', 'description': 'An awesome badge only awarded to awesome people or non-existent test entities', 'criteria': 'http://wikipedia.org/Awesome', } with open(self.get_testfiles_path('300x300.png'), 'r') as badge_image: post_response = self.client.post('/v1/issuer/issuers/{issuer}/badges'.format(issuer=test_issuer.entity_id), dict(badgeclass_props, image=badge_image), ) self.assertEqual(post_response.status_code, 201) slug = post_response.data.get('slug') with open(self.get_testfiles_path('450x450.png'), 'r') as new_badge_image: put_response = self.client.put('/v1/issuer/issuers/{issuer}/badges/{badge}'.format(issuer=test_issuer.entity_id, badge=slug), dict(badgeclass_props, image=new_badge_image), format='multipart' ) self.assertEqual(put_response.status_code, 200) new_badgeclass = BadgeClass.objects.get(entity_id=slug) image_width, image_height = get_image_dimensions(new_badgeclass.image.file) # File should be changed to new 450x450 image self.assertEqual(image_width, 450) self.assertEqual(image_height, 450)
def check_min_image_size(self, limit): """ 验证上传的图片尺寸是否小于最小限制 """ for image in self.files: w, h = get_image_dimensions(image) if w < limit[0] or h < limit[1]: self.error = u'上传的图片尺寸太小(最小{0}x{1})'.format(*limit) return False return True
def validate_image(fieldfile_obj): if fieldfile_obj: w, h = get_image_dimensions(fieldfile_obj) if w < 100: raise ValidationError( "The image is %i pixel narrow. It's supposed to be wider than 100px" % w) if h < 100: raise ValidationError( "The image is %i pixel low. It's supposed to be higher than 100px" % h)
def test_bug_19457(self): """ Regression test for #19457 get_image_dimensions fails on some pngs, while Image.size is working good on them """ img_path = os.path.join(os.path.dirname(upath(__file__)), "magic.png") try: size = get_image_dimensions(img_path) except zlib.error: self.fail("Exception raised from get_image_dimensions().") self.assertEqual(size, Image.open(img_path).size)
def validate_image(imageField): filesize = imageField.file.size w, h = get_image_dimensions(imageField) if w < 1280: raise ValidationError( f"The image is {w} pixel wide. It should be greater than or equal to 1280px" ) if h < 640: raise ValidationError( f"The image is {h} pixel high. It should be greater than or equal to 640px" )
def clean_logo_file(self): picture = self.cleaned_data.get("logo_file") if picture: try: w, h = get_image_dimensions(picture) if w > 252 or h > 137: raise forms.ValidationError( _('Your customer header is too big')) except TypeError: raise forms.ValidationError(_('Unsupported format')) return picture
def clean_student_image(self): picture = self.cleaned_data['student_image'] if not picture: raise ValidationError("No image!") else: w, h = get_image_dimensions(picture) if w > 450: raise ValidationError("Upload a max of 450px wide photo") if h > 450: raise ValidationError("Upload a photo of max height 450px") return picture
def save(self, name, content, save=True): # Repopulate the image dimension cache. self._dimensions_cache = get_image_dimensions(content) # Update width/height fields, if needed if self.field.width_field: setattr(self.instance, self.field.width_field, self.width) if self.field.height_field: setattr(self.instance, self.field.height_field, self.height) super(ImageFieldFile, self).save(name, content, save)
def clean_new_image(self): new_image = self.cleaned_data.get('new_image') if not new_image: raise forms.ValidationError("No image!") else: w, h = get_image_dimensions(new_image) if w < 110: raise forms.ValidationError("The image is %i pixel wide. It's supposed to be more than 110px" % w) if h < 110: raise forms.ValidationError("The image is %i pixel high. It's supposed to be more than 110px" % h) return new_image
def clean_profile_photo(self): photo = self.cleaned_data.get('profile_photo') w, h = get_image_dimensions(photo) min_width, min_height = 300, 300 if w != h: raise forms.ValidationError('Image should be square') if w < min_width or h < min_height: raise forms.ValidationError(('Image should be at least {}x{}' \ ' pixels').format(min_width, min_height)) return photo
def check_resolution(self): """ Проверяет разрешение изображения. :return True: если разрешение меньше 800x800 :return False: если разрешение больше 800x800 """ image = self.cleaned_data['image'] width, height = get_image_dimensions(image) if width > 1600 or height > 1600: return False return True
def clean_businesslogo(self): businesslogo = self.cleaned_data.get("businesslogo") if not businesslogo: raise forms.ValidationError("No image!") else: w, h = get_image_dimensions(businesslogo) if w != 400: raise forms.ValidationError("The image is %i pixel wide. It's supposed to be 400px" % w) if h != 300: raise forms.ValidationError("The image is %i pixel high. It's supposed to be 300px" % h) return businesslogo
def clean_image(self): image = self.cleaned_data['image'] if image: from django.core.files.images import get_image_dimensions w, h = get_image_dimensions(image) if w > 958 or h > 460: raise forms.ValidationError( u'That image is un suitable. The image needs to be width : 958px height :460px ' ) return image
def validate(self): cat_name = self.category.lower() print(cat_name) if Category.objects.filter(category=cat_name).exclude( id=self.id).exists(): raise ValidationError("Category name should be unique") width, height = get_image_dimensions(self.cat_img.file) ratio = width / height if ratio >= 1.6 or ratio <= 1.4: raise ValidationError("Image aspect ratio must be near 3:2")
def getImageDimensions(self): ''' Returns the dimensions of the uploaded image file. Borrows Django's django.core.files.images.get_image_dimensions method to get the dimensions via Pillow (python imaging module). ''' image_dimensions = get_image_dimensions(self.file) width = image_dimensions[0] height = image_dimensions[1] return width, height
def save(self, *args, **kwargs): if self.image: width, height = get_image_dimensions(self.image.open().file, close=False) self.image_width = width self.image_height = height else: self.image_width = 0 self.image_height = 0 super(BlogPost, self).save(*args, **kwargs)
def clean(self): super(AdImageInlineForm, self).clean() device = self.cleaned_data.get('device', None) image = self.cleaned_data.get('image', None) ad = self.cleaned_data.get('ad', None) if image and device and ad: allowed_size = settings.ADS_ZONES.get(ad.zone, {}). \ get('ad_size', {}). \ get(device, settings.ADS_DEFAULT_AD_SIZE) allowed_w, allowed_h = [int(d) for d in allowed_size.split('x')] w, h = get_image_dimensions(image)
def image_is_panoramic(self): """Return True if the image has a 3:2 ratio or bigger.""" try: img_width, img_height = get_image_dimensions(self.image.file) # Images go in a 427x286 box -> 3:2 ratio if (img_width / img_height) >= 1.5: panoramic = True else: panoramic = False except Exception: panoramic = True return panoramic
def get_file_info(file): ret = dict() ret["extension"] = file.name.split(".")[-1] ret["name"] = file.name ret["size"] = file.size ret["content_type"] = file.content_type if file.content_type.startswith("image/"): w, h = get_image_dimensions(file) ret["width"] = w ret["height"] = h # print("get_file_info: ", ret) return ret
def validate_rectangle_gondola(image): """ Raise a validation error if the gondola image is not a valid rectangle (580 x 290). :param image: image field :return: image """ allowed_size = (580, 280) img_size = get_image_dimensions(image) if img_size not in allowed_size: raise ValidationError('Gondola image should be a rectangle %s instead' 'of %s' % (allowed_size, img_size))
def validate_picture(self, cleaned_data): picture = cleaned_data['appliance_icon'] logger.debug('Icon uploaded: %s', picture) if picture: w, h = get_image_dimensions(picture) if (w > 150) or (h > 150): self.add_error('appliance_icon', 'Icon must be 150px by 150px or smaller.') logger.debug('Icon uploaded is larger than 150px by 150px.') logger.debug('Icon uploaded is valid.') elif not picture: logger.debug('Icon not uploaded.')
def is_valid(self): """" Redefine es is_valid() y aumenta la validacion del tamanio de la imagen """ result = super(self.__class__, self).is_valid() if result: (width, height) = get_image_dimensions(self.cleaned_data['foto']) if not (width >= 1600 or height >= 1600): return (False, 'La imagen debe tener algún lado de\ 1600 píxeles como mínimo') return (result, '')
def get_or_create_image(image_path): image = default_storage.get_image_by_path(image_path) if not image: image_file = default_storage.open(image_path) width, height = get_image_dimensions(image_file) image = Image.objects.create( title=os.path.basename(image_path), width=width, height=height, file=image_path, ) return image
def is_valid(self): """ Redefine es is_valid() y aumenta la validacion del tamanio de la imagen """ result = super(self.__class__, self).is_valid() if result: (width, height) = get_image_dimensions(self.cleaned_data['foto']) #if not (width >= 1600 or height >= 1600): #if not (width >= 960 or height >= 960): # return (False, _(u'Your photo must measure at least 960 pixels in length or width.')) return (result, '')
def test_invalid_image(self): """ get_image_dimensions() should return (None, None) for the dimensions of invalid images (#24441). brokenimg.png is not a valid image and it has been generated by: $ echo "123" > brokenimg.png """ img_path = os.path.join(os.path.dirname(__file__), "brokenimg.png") with open(img_path, 'rb') as fh: size = images.get_image_dimensions(fh) self.assertEqual(size, (None, None))
def test_can_edit_with_discovery_edit_permission(self): uploaded_photo = get_uploaded_file('transparent.png') item = PrimaryHeroImage.objects.create(custom_image=uploaded_photo) self.detail_url = reverse( 'admin:discovery_primaryheroimageupload_change', args=(item.pk,) ) user = user_factory(email='*****@*****.**') self.grant_permission(user, 'Discovery:Edit') self.client.login(email=user.email) response = self.client.get(self.detail_url, follow=True) assert response.status_code == 200 content = response.content.decode('utf-8') assert 'transparent.jpg' in content updated_photo = get_uploaded_file('preview_4x3.jpg') response = self.client.post( self.detail_url, dict(custom_image=updated_photo), follow=True ) assert response.status_code == 200 item.reload() assert PrimaryHeroImage.objects.count() == 1 assert item.custom_image == 'hero-featured-image/preview_4x3.jpg' assert os.path.exists( os.path.join(settings.MEDIA_ROOT, 'hero-featured-image', 'preview_4x3.jpg') ) assert os.path.exists( os.path.join( settings.MEDIA_ROOT, 'hero-featured-image', 'thumbs', 'preview_4x3.jpg' ) ) width, height = get_image_dimensions( os.path.join(settings.MEDIA_ROOT, 'hero-featured-image', 'preview_4x3.jpg') ) t_width, t_height = get_image_dimensions( os.path.join( settings.MEDIA_ROOT, 'hero-featured-image', 'thumbs', 'preview_4x3.jpg' ) ) assert width <= 960 and height <= 640 assert t_width <= 150 and t_height <= 120
def new(request): if request.method == "POST": form = NewImageForm(request.POST, request.FILES) if form.is_valid(): if form.cleaned_data[ 'imageFile'] and not form.cleaned_data['imageName']: image = form.cleaned_data['imageFile'] name = image.name width, height = get_image_dimensions(image) elif form.cleaned_data[ 'imageName'] and not form.cleaned_data['imageFile']: img = get_remote_image(form.cleaned_data['imageName']) if img is None: error = "Неверная ссылка" return render(request, "new.html", { 'form': form, 'error': error }) image = img['im'] name = img['name'] width, height = get_image_dimensions(img['im']) else: error = "Можно использовать только один способ загрузки изображения" return render(request, "new.html", { 'form': form, 'error': error }) result = Img.objects.create(image=image, name=name, width=width, height=height) return redirect("img_view", img_id=result.pk) else: form = NewImageForm() return render(request, "new.html", {'form': form})
def save(self, *args, **kwargs): if (not self.exif_time_taken) or (not self.exif_lat) or ( not self.exif_lon): tags = exifread.process_file(self.image, details=False) if 'EXIF DateTimeOriginal' in tags: date_time_obj = datetime.datetime.strptime( str(tags['EXIF DateTimeOriginal']), '%Y:%m:%d %H:%M:%S') self.exif_time_taken = date_time_obj lat, lon = get_exif_location(tags) if lat: self.exif_lat = round(lat, 5) if lon: self.exif_lon = round(lon, 5) super(Photo, self).save(*args, **kwargs) exif_fullhd = piexif.load(self.image.path) if '0th' in exif_fullhd: width, height = get_image_dimensions(self.image_fullhd.file) exif_fullhd['0th'][256] = width exif_fullhd['0th'][257] = height if '1st' in exif_fullhd: del exif_fullhd['1st'] if 'thumbnail' in exif_fullhd: del exif_fullhd['thumbnail'] # Fix S10 Mini photos if ('Exif' in exif_fullhd) and (41729 in exif_fullhd['Exif']): del exif_fullhd['Exif'][41729] exif_thumb = piexif.load(self.image.path) if '0th' in exif_thumb: width, height = get_image_dimensions(self.image_thumb.file) exif_thumb['0th'][256] = width exif_thumb['0th'][257] = height if '1st' in exif_thumb: del exif_thumb['1st'] if 'thumbnail' in exif_thumb: del exif_thumb['thumbnail'] # Fix S10 Mini photos if ('Exif' in exif_thumb) and (41729 in exif_thumb['Exif']): del exif_thumb['Exif'][41729] piexif.insert(piexif.dump(exif_fullhd), self.image_fullhd.path) piexif.insert(piexif.dump(exif_thumb), self.image_thumb.path)
def validate_video_image(image_file): """ Validates video image file. Arguments: image_file: The selected image file. Returns: error (String or None): If there is error returns error message otherwise None. """ error = None if not all(hasattr(image_file, attr) for attr in ['name', 'content_type', 'size']): error = _('The image must have name, content type, and size information.') elif image_file.content_type not in settings.VIDEO_IMAGE_SUPPORTED_FILE_FORMATS.values(): error = _('This image file type is not supported. Supported file types are {supported_file_formats}.').format( supported_file_formats=settings.VIDEO_IMAGE_SUPPORTED_FILE_FORMATS.keys() ) elif image_file.size > settings.VIDEO_IMAGE_SETTINGS['VIDEO_IMAGE_MAX_BYTES']: error = _('This image file must be smaller than {image_max_size}.').format( image_max_size=settings.VIDEO_IMAGE_MAX_FILE_SIZE_MB ) elif image_file.size < settings.VIDEO_IMAGE_SETTINGS['VIDEO_IMAGE_MIN_BYTES']: error = _('This image file must be larger than {image_min_size}.').format( image_min_size=settings.VIDEO_IMAGE_MIN_FILE_SIZE_KB ) else: try: image_file_width, image_file_height = get_image_dimensions(image_file) except TypeError: return _('There is a problem with this image file. Try to upload a different file.') if image_file_width is None or image_file_height is None: return _('There is a problem with this image file. Try to upload a different file.') image_file_aspect_ratio = abs(image_file_width / float(image_file_height) - settings.VIDEO_IMAGE_ASPECT_RATIO) if image_file_width < settings.VIDEO_IMAGE_MIN_WIDTH or image_file_height < settings.VIDEO_IMAGE_MIN_HEIGHT: error = _('Recommended image resolution is {image_file_max_width}x{image_file_max_height}. ' 'The minimum resolution is {image_file_min_width}x{image_file_min_height}.').format( image_file_max_width=settings.VIDEO_IMAGE_MAX_WIDTH, image_file_max_height=settings.VIDEO_IMAGE_MAX_HEIGHT, image_file_min_width=settings.VIDEO_IMAGE_MIN_WIDTH, image_file_min_height=settings.VIDEO_IMAGE_MIN_HEIGHT ) elif image_file_aspect_ratio > settings.VIDEO_IMAGE_ASPECT_RATIO_ERROR_MARGIN: error = _('This image file must have an aspect ratio of {video_image_aspect_ratio_text}.').format( video_image_aspect_ratio_text=settings.VIDEO_IMAGE_ASPECT_RATIO_TEXT ) else: try: image_file.name.encode('ascii') except UnicodeEncodeError: error = _('The image file name can only contain letters, numbers, hyphens (-), and underscores (_).') return error
def test_valid_image(self): """ get_image_dimensions() should catch struct.error while feeding the PIL Image parser (#24544). Emulates the Parser feed error. Since the error is raised on every feed attempt, the resulting image size should be invalid: (None, None). """ img_path = os.path.join(os.path.dirname(__file__), "test.png") with mock.patch('PIL.ImageFile.Parser.feed', side_effect=struct.error): with open(img_path, 'rb') as fh: size = images.get_image_dimensions(fh) self.assertEqual(size, (None, None))
def clean_image(self): image = self.cleaned_data.get('image') # only 1000000 bytes max size is allowed if image.size > 1000000: raise ValidationError( 'Размер изображения не должен превышать 1 мегабайта!') # only 1×1 format is allowed width, height = get_image_dimensions(image) if width != height: raise ValidationError('Формат изображения должен быть 1×1!') return image