def __init__(self, width=None, height=None, anchor=None, crop=None, upscale=None, **kwargs): self.processors = [ ThumbnailProcessor(width, height, anchor=anchor, crop=crop, upscale=upscale) ] source = kwargs.get('source') if not (source is not None and getattr(source, 'name', None)): random_image = get_random_image() media_root = os.path.abspath(django_settings.MEDIA_ROOT) static_root = os.path.abspath(django_settings.STATIC_ROOT) source = ImageCacheFile(self, name=random_image) source.name = source.file.name \ .replace(media_root, '') \ .replace(static_root, '')[1:] kwargs['source'] = source super(DummyThumbnail, self).__init__(**kwargs)
def generic_cached_admin_thumb(instance): image = instance.images.first() if image: cached = ImageCacheFile(AdminThumbnailSpec(image.image_file)) cached.generate() return cached return None
def add_thumb_if_not_none(files, field): from imagekit.cachefiles import ImageCacheFile if field: image_generator = U24Thumbnail(source=field.file) file = ImageCacheFile(image_generator) file.generate() files.append(os.path.join(settings.MEDIA_ROOT, file.name))
def get_thumb_url(field: ImageFieldFile): from imagekit.cachefiles import ImageCacheFile if field: image_generator = PreviewThumbnail(source=field.file) file = ImageCacheFile(image_generator) file.generate() return file.url return None
def cached_admin_thumb(instance): if instance.img: # `image` is the name of the image field on the model cached = ImageCacheFile(AdminThumbnailSpec(instance.img)) # only generates the first time, subsequent calls use cache cached.generate() return cached return ""
def cached_list_thumb(instance): # 'image' is the name of the image field on the model cached = '' if instance.image: cached = ImageCacheFile(ListThumbnail(instance.image)) # only generates the first time, subsequent calls use cache cached.generate() return cached
def _crop_image(self): if not self.is_image: raise Attachment.NotAnImageException("Attachment is not an image. Use is_image to check" " if attachment is an image before asking for the " "cropped version.") generator = Attachment.CroppedImage(source=self.file) cache_file = ImageCacheFile(generator) try: cache_file.generate() except FileNotFoundError as e: logger.warn("File not found when generating cache file: " + str(e)) return cache_file
def source_group_receiver(self, sender, source, signal, **kwargs): """ Relay source group signals to the appropriate spec strategy. """ from imagekit.cachefiles import ImageCacheFile source_group = sender # Ignore signals from unregistered groups. if source_group not in self._source_groups: return #OVERRIDE HERE -- pass specs into generator object specs = [ generator_registry.get(id, source=source, specs=spec_data_field_hash[id]) for id in self._source_groups[source_group] ] callback_name = self._signals[signal] #END OVERRIDE for spec in specs: file = ImageCacheFile(spec) call_strategy_method(file, callback_name)
def source_group_receiver(self, sender, source, signal, **kwargs): """ Relay source group signals to the appropriate spec strategy. """ from imagekit.cachefiles import ImageCacheFile source_group = sender instance = kwargs['instance'] # Ignore signals from unregistered groups. if source_group not in self._source_groups: return #HOOK -- update source to point to image file. for id in self._source_groups[source_group]: spec_to_update = generator_registry.get(id, source=source, instance=instance, field=hack_spec_field_hash[id]) specs = [generator_registry.get(id, source=source, instance=instance, field=hack_spec_field_hash[id]) for id in self._source_groups[source_group]] callback_name = self._signals[signal] # print 'callback_name? %s'%(callback_name) for spec in specs: file = ImageCacheFile(spec) # print 'SEPC %s file %s'%(spec, file) call_strategy_method(file, callback_name)
def test_no_source_falsiness(): """ Ensure cache files generated from sourceless specs are falsy. """ spec = TestSpec(source=None) file = ImageCacheFile(spec) assert_file_is_falsy(file)
def test_async_backend_falsiness(): """ Ensure that a cachefile with an asynchronous cache file backend is falsy. """ spec = TestSpec(source=get_unique_image_file()) file = ImageCacheFile(spec, cachefile_backend=DummyAsyncCacheFileBackend()) assert_file_is_falsy(file)
def test_cachefiles(): spec = TestSpec(source=get_unique_image_file()) file = ImageCacheFile(spec) file.url # remove link to file from spec source generator # test __getstate__ of ImageCacheFile file.generator.source = None pickleback(file)
def get(self, request, *args, **kwargs): photo = self.get_object() width = int(request.GET.get('w', photo.image.width)) height = int(request.GET.get('h', photo.image.height)) style = request.GET.get('s', 'fill') proc = CROP_STYLES.get(style, ResizeToFill) spec = CropSpec(source=photo.image) spec.processors = [proc(width, height)] icf = ImageCacheFile(spec) icf.generate() return HttpResponseRedirect(icf.url)
def get_image_cache_file(): storage = Mock(FileSystemStorage) backend = SimpleCFBackend() strategy = OptimisticStrategy() generator = ImageGenerator() return ImageCacheFile(generator, storage=storage, cachefile_backend=backend, cachefile_strategy=strategy)
def test_sync_backend_truthiness(): """ Ensure that a cachefile with a synchronous cache file backend (the default) is truthy. """ spec = TestSpec(source=get_unique_image_file()) file = ImageCacheFile(spec) assert_file_is_truthy(file)
def _get_SIZE_url(self, size): photosize = PhotoSizeCache().sizes.get(size) if not self.size_exists(photosize): self.create_size(photosize) if photosize.increment_count: self.increment_count() generator = PhotologueSpec(photo=self, photosize=photosize) image_url = urlparse.urljoin(self.image.url, 'f') cache = ImageCacheFile(generator) return cache.url
def thumb(content, thumb_type=None): """A filter to return an image file used to preview a Content as a thumbnail. The particular image selected depends on the type of Content. """ image = None # The ImageField that we're using as a source for the thumbnail if ( isinstance(content, models.Story) or isinstance(content, models.Video) ) and content.cover: image = content.cover.source elif isinstance(content, models.Image): image = content.source elif isinstance(content, models.Gallery) and content.entries.count() > 0: # Gallery cache currently messed up, so no thumbnail for now # image = thumb(content.entries_in_order()[0]) return content.entries_in_order()[0].source.url if image is None: return None if thumb_type is None: return True # Check which thumbnail generator we're using klass = { "small": SmallThumbnail, "medium": MediumThumbnail, "large": LargeThumbnail, "huge": HugeThumbnail, }[thumb_type] # Make the thumbnail generator and cache the result try: generator = klass(source=image) cached_file = ImageCacheFile(generator) cached_file.generate() # This seems to be necessary to save the file return cached_file.url except FileNotFoundError: return None except (IOError, SyntaxError): # Error actually parsing the file return image.url
def handle(self, *args, **options): generators = generator_registry.get_ids() if args: patterns = self.compile_patterns(args) generators = (id for id in generators if any( p.match(id) for p in patterns)) for generator_id in generators: self.stdout.write('Validating generator: %s\n' % generator_id) try: for image_file in cachefile_registry.get(generator_id): if image_file.name: self.stdout.write(' %s\n' % image_file.name) try: image_file.generate() except Exception as err: self.stdout.write('\tFailed %s\n' % (err)) except: items = cachefile_registry._cachefiles.items() for k, v in items: if generator_id in v: #k is SourceGroupFilesGenerator model_class = k.source_group.model_class image_field = k.source_group.image_field all_objects = model_class.objects.all() item_count = len(all_objects) count = 0 for instance in all_objects: count += 1 print try: source = getattr(instance, image_field) specs = spec_data_field_hash[generator_id] spec = generator_registry.get(generator_id, source=source, specs=specs) file = ImageCacheFile(spec) self.stdout.write(' [%s of %s] - %s\n' % (count, item_count, file)) call_strategy_method(file, 'on_source_saved') except Exception: self.stdout.write('ERROR: %s\n' % (traceback.format_exc()))
def test_cachefiles(): clear_imagekit_cache() spec = TestSpec(source=get_unique_image_file()) file = ImageCacheFile(spec) file.url # remove link to file from spec source generator # test __getstate__ of ImageCacheFile file.generator.source = None restored_file = pickleback(file) assert file is not restored_file # Assertion for #437 and #451 assert file.storage is restored_file.storage
def test_repr_does_not_send_existence_required(): """ Ensure that `__repr__` method does not send `existance_required` signal Cachefile strategy may be configured to generate file on `existance_required`. To generate images, backend passes `ImageCacheFile` instance to worker. Both celery and RQ calls `__repr__` method for each argument to enque call. And if `__repr__` of object will send this signal, we will get endless recursion """ with mock.patch('imagekit.cachefiles.existence_required') as signal: # import here to apply mock from imagekit.cachefiles import ImageCacheFile spec = TestSpec(source=get_unique_image_file()) file = ImageCacheFile(spec, cachefile_backend=DummyAsyncCacheFileBackend()) file.__repr__() eq_(signal.send.called, False)
def generate_images(self, force_create=False): """ Generate resized images from the master :param bool force_create: Create thumbnail, small, and medium images even if they already exist """ if self.original: base_name = self.original.name if force_create or not self.thumbnail: try: image_generator = SightingImageThumbnail(source=self.original) filename = u'%s.thumbnail.jpg' % base_name result = ImageCacheFile(image_generator, name=filename) #.generate() result.generate() self.thumbnail.name = filename self.save() finally: self.original.close() #self.thumbnail.close() if force_create or not self.small: try: image_generator = SightingImageSmall(source=self.original) filename = u'%s.small.jpg' % base_name result = ImageCacheFile(image_generator, name=filename) #.generate() result.generate() self.small.name = filename self.save() finally: self.original.close() #self.small.close() if force_create or not self.medium: try: image_generator = SightingImageMedium(source=self.original) filename = u'%s.medium.jpg' % base_name result = ImageCacheFile(image_generator, name=filename) #.generate() result.generate() self.medium.name = filename self.save() finally: self.original.close()
def __get__(self, instance, owner): # print 'get %s - %s. attname: %s field %s source_field_name: %s'%(instance, owner, self.attname, self.field, self.source_field_name) if instance is None: return self.field else: source = getattr(instance, self.source_field_name) spec = self.field.get_spec(source=source, instance=instance) file = ImageCacheFile(spec) instance.__dict__[self.attname] = file return file
def test_repr_does_not_send_existence_required(): """ Ensure that `__repr__` method does not send `existance_required` signal Cachefile strategy may be configured to generate file on `existance_required`. To generate images, backend passes `ImageCacheFile` instance to worker. Both celery and RQ calls `__repr__` method for each argument to enque call. And if `__repr__` of object will send this signal, we will get endless recursion """ with mock.patch('imagekit.cachefiles.existence_required') as signal: # import here to apply mock from imagekit.cachefiles import ImageCacheFile spec = TestSpec(source=get_unique_image_file()) file = ImageCacheFile( spec, cachefile_backend=DummyAsyncCacheFileBackend() ) file.__repr__() eq_(signal.send.called, False)
def _local_image_url(self, size): """ Generate the URL of an image of a particular size, hosted locally, based on the original file (which must already be downloaded). """ if self.original_file: if size == 'original': return self.original_file.url else: generator = self.PHOTO_SIZES[size]['generator'] try: image_generator = generator(source=self.original_file) result = ImageCacheFile(image_generator) return result.url except: # We have an original file but something's wrong with it. # Might be 0 bytes or something. return static('img/original_error.jpg') else: # We haven't downloaded an original file for this Photo. return static('img/original_missing.jpg')
def _local_image_url(self, size): """ Generate the URL of an image of a particular size, hosted locally, based on the original file (which must already be downloaded). size -- one of 'large', 'medium', 'small', or 'thumbnail'. """ if self.image_file: if size == 'large': # Essentially the original file. return self.image_file.url else: generator = self.IMAGE_SIZES[size]['generator'] try: image_generator = generator(source=self.image_file) result = ImageCacheFile(image_generator) return result.url except: # We have an original file but something's wrong with it. # Might be 0 bytes or something. return static('img/original_error.jpg') else: # We haven't downloaded an original file for this. return static('img/original_missing.jpg')
def generate_thumbnail(self, source, **kwargs): generator = generator_registry.get(self.generator_id, source=source, **kwargs) return ImageCacheFile(generator)
def test_no_source_error(): spec = TestSpec(source=None) file = ImageCacheFile(spec) file.generate()
def cached_default(self): generator = ImageCacheFile(self.default) return generator.generate()
def test_accessor_methods_filename(self): generator = PhotologueSpec(photo=self.pl, photosize=self.s) cache = ImageCacheFile(generator) self.assertEqual(self.pl.get_testPhotoSize_filename(), cache.file.name)
def cached_preview(self): generator = ImageCacheFile(self.preview) return generator.generate()
def cached_tiny_thumb(self): generator = ImageCacheFile(self.tiny_thumb) return generator.generate()
def cached_bigger(self): generator = ImageCacheFile(self.bigger) return generator.generate()
def get_image(self, image, w, h): generator = self.get_generator(w, h)(source=image) file = ImageCacheFile(generator) file.generate() return file
def create_size(self, photosize): generator = PhotologueSpec(photo=self, photosize=photosize) cache = ImageCacheFile(generator) cache.generate()
def _get_SIZE_filename(self, size): photosize = PhotoSizeCache().sizes.get(size) generator = PhotologueSpec(photo=self, photosize=photosize) cache = ImageCacheFile(generator) return cache.name
def cached_admin_thumb(instance): cached = ImageCacheFile(AdminThumbnailSpec(instance.image)) cached.generate() return cached
def cached_full_fixed(self): generator = ImageCacheFile(self.full_fixed) return generator.generate()