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, width=50, height=50, adjustment='fit')
		t = Template("{% load daguerre %}{% adjust image width=50 height=50 adjustment='fit' %}")
		c = Context({'image': adjusted.adjusted})
		self.assertEqual(t.render(c), helper.info_dict()['url'])
 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], [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.info_dicts()[0][1]['url']))
 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 Exception:
                # 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
Example #5
0
    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
    def adjust(self):
        # May raise IOError.

        # First try to fetch a version that already exists.
        kwargs = self.get_query_kwargs()
        try:
            return AdjustedImage.objects.filter(**kwargs)[:1][0]
        except IndexError:
            pass

        # If that fails, try to create one from the storage path.
        # Raises IOError if something goes wrong.
        adjustment = self.adjustment_for_path(self.storage_path)
        im = adjustment.adjust()

        creation_kwargs = {}
        for k, v in kwargs.iteritems():
            if k.endswith('__isnull'):
                creation_kwargs[k[:-len('__isnull')]] = None
            else:
                creation_kwargs[k] = v

        adjusted = AdjustedImage(**creation_kwargs)
        f = adjusted._meta.get_field('adjusted')

        format = (adjustment.format
                  if adjustment.format in KEEP_FORMATS else DEFAULT_FORMAT)
        args = (unicode(creation_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)[:1][0]
        except IndexError:
            adjusted.adjusted = final_path
            adjusted.save()
        else:
            default_storage.delete(final_path)
        return adjusted