Skip to content

Instantly share code, notes, and snippets.

@cryzed
Last active October 1, 2018 22:04
Show Gist options
  • Save cryzed/e6565565dab8b32ca3c4ab63bcd2c29d to your computer and use it in GitHub Desktop.
Save cryzed/e6565565dab8b32ca3c4ab63bcd2c29d to your computer and use it in GitHub Desktop.
import os
import magic
from atom.api import Atom, Bytes, Int, List, Str, observe
from enaml.image import Image
# https://pypi.org/project/natsort/
from natsort import natsorted
class ImageFolder(Atom):
path = Str()
image_data = Bytes()
items = List(str)
index = Int(default=0)
_supported_formats = set(Image.format.items).union({'jpeg'}) - {'auto'}
def _load_image(self):
if self.items:
with open(self.items[self.index], 'rb') as file:
self.image_data = file.read()
@observe('path')
def _on_path(self, change):
# Clear image, items, and reset index
self.image_data = b''
self.items.clear()
self.index = 0
# If the path is empty or doesn't exist just return
path = change['value']
if not os.path.isdir(path):
return
# Collect all images recursively
for root, folders, file_names in os.walk(path):
for file_name in file_names:
path = os.path.join(root, file_name)
mime = magic.from_file(path, mime=True)
kind, format = mime.split('/', 1)
if kind == 'image' and format in self._supported_formats:
self.items.append(path)
self.items = natsorted(self.items)
self._load_image()
def next(self):
self.index += 1
if self.index >= len(self.items):
self.index = 0
self._load_image()
def previous(self):
self.index -= 1
if self.index < 0:
self.index = len(self.items) - 1
self._load_image()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment