def test_file(self): # Tag should accept an :class:`ImageFieldFile` as its argument. storage_path = self.create_image('100x100.png') adjusted = AdjustedImage() adjusted.adjusted = storage_path helper = AdjustmentHelper([storage_path], generate=False) helper.adjust('fit', width=50, height=50) t = Template("{% load daguerre %}{% adjust image 'fit' width=50 " "height=50 as adj %}{{ adj }}") c = Context({'image': adjusted.adjusted}) self.assertEqual(t.render(c), escape(helper[0][1]['url']))
def _generate(self, storage_path): # May raise IOError if the file doesn't exist or isn't a valid image. # If we're here, we can assume that the adjustment doesn't already # exist. Try to create one from the storage path. Raises IOError if # something goes wrong. kwargs = { 'requested': self.requested, 'storage_path': storage_path } with default_storage.open(storage_path, 'rb') as im_file: im = Image.open(im_file) try: im.verify() except (IndexError, struct.error, SyntaxError): # Raise an IOError if the image isn't valid. raise IOError im_file.seek(0) im = Image.open(im_file) im.load() format = im.format if im.format in KEEP_FORMATS else DEFAULT_FORMAT if self.adjust_uses_areas: areas = self.get_areas(storage_path) else: areas = None for adjustment in self.adjustments: im = adjustment.adjust(im, areas=areas) adjusted = AdjustedImage(**kwargs) f = adjusted._meta.get_field('adjusted') args = (six.text_type(kwargs), datetime.datetime.now().isoformat()) filename = '.'.join((make_hash(*args, step=2), format.lower())) storage_path = f.generate_filename(adjusted, filename) final_path = save_image(im, storage_path, format=format, storage=default_storage) # Try to handle race conditions gracefully. try: adjusted = AdjustedImage.objects.filter(**kwargs ).only('adjusted')[:1][0] except IndexError: adjusted.adjusted = final_path adjusted.save() else: default_storage.delete(final_path) return adjusted