Skip to content

Instantly share code, notes, and snippets.

@panzi
Last active November 13, 2026 00:04
Show Gist options
  • Select an option

  • Save panzi/898d61b65dd4a84e635addb346fc7002 to your computer and use it in GitHub Desktop.

Select an option

Save panzi/898d61b65dd4a84e635addb346fc7002 to your computer and use it in GitHub Desktop.
Very simple function to display a grid of images in Jupyter notebooks (HTML only).
#!/usr/bin/env python3
import json
from PIL.Image import Image, open as open_image
from html import escape as h
from pathlib import Path
from uuid import uuid4
from io import BytesIO
from base64 import b64encode
from shutil import copy
from urllib.parse import quote as urlquote
from os.path import splitext
try:
from IPython.display import display, HTML # type: ignore
except ImportError:
def HTML(html):
return html
def display(*args):
print(*args)
__all__ = 'image_grid', 'make_image_grid',
def make_image_grid(images: list[Image|str|Path], thumb_width: int=150, thumb_height: int=150, output_dir: str|Path|None=None, cache_busting: bool=True) -> str:
list_id = f"panzi-image-grid-list-{uuid4()}"
html: list[str]=[
f'''\
<style>
.panzi-image-grid-list {{ list-style:none; margin:0 !important; padding:0 !important; display:flex; flex-wrap:wrap; gap: 1rem; }}
.panzi-image-grid-list li {{ display: inline-block; margin:0; padding:0; }}
.panzi-image-grid-list figure > a {{ text-decoration: none; display: block; }}
.panzi-image-grid-list img {{ border: none; display: block; }}
.panzi-image-grid-list figure {{ margin:0; padding:0; }}
.panzi-image-grid-list figcaption {{ text-align: center; }}
#{h(list_id)} img {{ width: {h(str(thumb_width))}px; height: {h(str(thumb_height))}px; object-fit: contain; }}
</style>
<ul class="panzi-image-grid-list" id="{h(list_id)}">'''
]
thumb_size = (thumb_width, thumb_height)
bio = BytesIO()
out_dir = Path(output_dir) if isinstance(output_dir, str) else output_dir
web_out_dir: str|None = None
if out_dir is not None:
if out_dir.is_absolute():
raise ValueError(f'output_dir is supposed to be a relative path: {output_dir!r}')
web_out_dir = '/'.join(map(urlquote, out_dir.parts))
out_dir.mkdir(parents=True, exist_ok=True)
img_names: set[str] = set()
def make_unique_name(img_name: str) -> str:
if img_name in img_names:
prefix, suffix = splitext(img_name)
img_index = 0
while img_name in img_names:
img_index += 1
img_name = f'{prefix} ({img_index}){suffix}'
return img_name
for index, img_or_path in enumerate(images):
if isinstance(img_or_path, (str, Path)):
img_path = Path(img_or_path)
thumb = open_image(img_path)
alt = img_path.name
if out_dir is None:
data = img_path.read_bytes()
full_url = f'data:image/png;base64,{b64encode(data).decode("ASCII")}'
else:
img_name = make_unique_name(alt)
new_path = out_dir / img_name
copy(img_path, new_path)
full_url = f'/files/{web_out_dir}/{urlquote(img_name)}'
else:
thumb = img_or_path.copy()
bio.seek(0)
bio.truncate()
img_or_path.save(bio, 'png')
alt = f'Image {index + 1}'
data = bio.getvalue()
if out_dir is None:
full_url = f'data:image/png;base64,{b64encode(data).decode("ASCII")}'
else:
img_name = f'image{index + 1:03d}.png'
img_name = make_unique_name(img_name)
new_path = out_dir / img_name
new_path.write_bytes(data)
full_url = f'/files/{web_out_dir}/{urlquote(img_name)}'
thumb.thumbnail(thumb_size)
bio.seek(0)
bio.truncate()
thumb.save(bio, 'jpeg')
data = bio.getvalue()
if out_dir is None:
thumb_url = f'data:image/png;base64,{b64encode(data).decode("ASCII")}'
else:
thumb_name = f'thumb{index + 1:03d}.png'
thumb_name = make_unique_name(thumb_name)
new_path = out_dir / thumb_name
new_path.write_bytes(data)
thumb_url = f'/files/{web_out_dir}/{urlquote(thumb_name)}'
html.append(
'<li>'
'<figure>'
f'<a href="{h(full_url)}" target="_blank"><img src="{h(thumb_url)}" alt="{h(alt)}" /></a>'
'<figcaption>'
f'{h(alt)}'
'</figcaption>'
'</figure>'
'</li>'
)
html.append('</ul>')
if out_dir is not None:
url_suffix = f" + '&_=' + Date.now()" if cache_busting else ''
html.append('''\
<script>
/* <![CDATA[ */
(function() {
const cookies = {};
if (document.cookie) {
for (const cookie of document.cookie.split(';')) {
const parts = cookie.split("=");
cookies[parts[0]] = parts.slice(1).join("=");
}
}
const xsrf = cookies._xsrf;
if (xsrf) {
const listId = ''' + json.dumps(list_id) + ''';
const list = document.getElementById(listId);
list.querySelectorAll('a[href^="/"]').forEach(e => {
e.href += '?_xsrf=' + xsrf''' + url_suffix + ''';
});
list.querySelectorAll('img[src^="/"]').forEach(e => {
e.src += '?_xsrf=' + xsrf''' + url_suffix + ''';
});
}
})();
/* ]]> */
</script>''')
return ''.join(html)
def image_grid(images: list[Image|str|Path], thumb_width: int=150, thumb_height: int=150, output_dir: str|Path|None=None, cache_busting: bool=True) -> None:
display(HTML(''.join(make_image_grid(images, thumb_width, thumb_height, output_dir, cache_busting))))
if __name__ == '__main__':
import argparse
ap = argparse.ArgumentParser()
ap.add_argument('-W', '--thumb-width', type=int, default=150)
ap.add_argument('-H', '--thumb-height', type=int, default=150)
ap.add_argument('-O', '--output-dir', default=None)
ap.add_argument('images', nargs='+')
args = ap.parse_args()
image_grid(args.images, args.thumb_width, args.thumb_height, args.output_dir)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment