def __init__(self, *args, **kwargs): super(CachedImageFile, self).__init__(*args, **kwargs) self._exists = ImageFile.exists(self) try: self._content = ImageFile.read(self) except Exception as exception: self._exception = exception else: self._exception = None
def get_image(self, source): """Get image.""" if not (source and source.exists()): random_image = get_random_image() random_file = open(random_image) source = ImageFile(random_file) buf = BytesIO(source.read()) image = Image.open(buf) # Fully load the image now to catch any problems with the image # contents. try: # An "Image file truncated" exception can occur for some images # that are still mostly valid -- we'll swallow the exception. image.load() except IOError: pass # Try a second time to catch any other potential exceptions. image.load() return image