Skip to content

Instantly share code, notes, and snippets.

@marcbelmont
Last active November 13, 2020 09:20
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save marcbelmont/063136bf28b6f2277be5bc27f57f978d to your computer and use it in GitHub Desktop.
Save marcbelmont/063136bf28b6f2277be5bc27f57f978d to your computer and use it in GitHub Desktop.
Browser based image viewer. Display all the images from a directory as thumbnails on a webpage.
#! /usr/bin/python3
import argparse
import imghdr
import webbrowser
from http.server import HTTPServer, SimpleHTTPRequestHandler
from os import chdir
from pathlib import Path
from urllib.parse import parse_qs, urlparse
def explore(root, args):
content = ''
images = 0
height = int(args.get('height', ['200'])[0])
for path in sorted(root.glob('*'), key=lambda x: (x.is_dir(), x.name)):
if path.is_dir():
content += explore(path, args)
continue
if not imghdr.what(path):
continue
content += f"""
<a href="{path}" data-fancybox="{str(root)}" data-caption="{path.name}">
<img src="{path}" class="float-left m-1" title="{path.name}" style="height: {height}px;" >
</a>
"""
images += 1
if images:
content = f'<div class="clearfix"></div><div class="text-light mt-3 mx-3" style="font-family: courier new">{root} ({images})</div>' + content
return content
class GetHandler(SimpleHTTPRequestHandler):
def log_message(self, format, *args):
pass
def do_GET(self):
components = urlparse(self.path)
if self.path.endswith('favicon.ico'):
return
if components.path != '/':
return super().do_GET()
args = parse_qs(components.query)
title = 'Image Viewer'
content = explore(Path('.'), args)
page = f"""
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>{title}</title>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css" integrity="sha384-JcKb8q3iqJ61gNV9KGb8thSsNjpSL0n8PARn9HuZOnIxN0hoP+VmmDGMN5t9UJ0Z" crossorigin="anonymous">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/gh/fancyapps/fancybox@3.5.7/dist/jquery.fancybox.min.css" />
</head>
<body style="background-color: #666;">
{content}
<script src="//code.jquery.com/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/gh/fancyapps/fancybox@3.5.7/dist/jquery.fancybox.min.js"></script>
</body>
</html>
"""
self.send_response(200)
self.end_headers()
self.wfile.write(page.encode('utf8'))
def parse_arguments():
parser = argparse.ArgumentParser(description='')
parser.add_argument('directory')
parser.add_argument('--port', default=8001)
parser.add_argument('--debug', action='store_true')
return parser.parse_args()
def main():
args = parse_arguments()
chdir(args.directory)
server = HTTPServer(('', args.port), GetHandler)
url = 'http://localhost:%d/?height=200' % args.port
print('Starting server on %s, use <Ctrl-C> to stop.' % url)
if not args.debug:
webbrowser.open(url)
try:
server.serve_forever()
except KeyboardInterrupt:
print('Seeya!')
if __name__ == '__main__':
main()
@marcbelmont
Copy link
Author

Browser based image viewer

Display all the images from a directory as thumbnails on a webpage. It will recursively collect images from sub-directories.

python image_viewer.py --help

Example:
python image_viewer.py ~/Downloads/my-images/

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment