Add thumbnails to a tarfile
I have shot quite a few GoPro images over the years. They are stored in tarfiles per recording session, so the folder name is the occasion where and when they were shot. With this many images I want to get a quick overview of the contents without processing the big images, so I want to generate thumbnails. And because the original images are in tarfiles I want to store the thumbnails in the same folder in a thumbnail tarfile.
This is the Python code using Pillow:
import io import tarfile from pathlib import Path from PIL import Image folder = Path.home() / "gopro/subfolder" with ( tarfile.open(folder / "images.tar") as tar_images, tarfile.open(folder / "thumbnails.tar", "w") as tar_thumbs, ): for member in tar_images: name = member.name print(name) # get image fp = tar_images.extractfile(member) # generate thumbnail im = Image.open(fp) im.thumbnail((256, 256)) with io.BytesIO() as f: # save to bytesio as jpeg im.save(f, format="JPEG") # generate a tarinfo object info = tarfile.TarInfo(name) # add length of data info.size = len(f.getvalue()) # move file pointer back to 0 f.seek(0, io.SEEK_SET) # add to thumbnail tarfile tar_thumbs.addfile(info, f)
The goal was to not use any temporary files on disk. So the image is loaded directly from the tarfile, a thumbnail is generated, stored in a BytesIO object and this is added to the thumbnail tarfile. The tarfile don't have compression enabled, because compressing JPEG doesn't bring that much, but costs CPU when using.