Skip to content

Instantly share code, notes, and snippets.

@vnznznz
Last active April 27, 2017 06:22
Show Gist options
  • Save vnznznz/6b26b12aeab0b4147cdd9e509f3ea8bd to your computer and use it in GitHub Desktop.
Save vnznznz/6b26b12aeab0b4147cdd9e509f3ea8bd to your computer and use it in GitHub Desktop.
Pack images in the current dir and subfolders for printing
#!usr/bin/python3
import os
from PIL import Image
from rectpack import newPacker
IMAGES = []
# to lazy to handle rotation right now
PACKER = newPacker(rotation=False)
# printers dont like pixels on the page border
# set to 0 if you dont want to print
OFFSET = 50
# 72 DPI 595 Pixels 842 Pixels
# 200 DPI 1654 Pixels 2339 Pixels
# 300 DPI 2480 Pixels 3508 Pixels
A4WIDTH = 1060
A4HEIGHT = 1500
print("WIDTH: %s HEIGHT: %s OFFSET: %s" % (A4WIDTH, A4HEIGHT, OFFSET))
print("loading images")
for folder in os.walk("."):
dirpath, dirnames, files = folder
for file in files:
# print("opening %s" % file)
if file.endswith(".JPG"):
img = Image.open(os.path.join(dirpath, file))
IMAGES.append(img)
print("loaded %s images" % len(IMAGES))
print("creating rects")
for i in range(len(IMAGES)):
img = IMAGES[i]
PACKER.add_rect(img.width, img.height, rid=i)
PACKER.add_bin(A4WIDTH - OFFSET * 2, A4HEIGHT - OFFSET * 2, count=100)
print("packing them images")
PACKER.pack()
print("exporting")
INDEX = 1
for rectbin in PACKER:
page = Image.new("RGB", (A4WIDTH, A4HEIGHT), "white")
for rect in rectbin:
img = IMAGES[rect.rid]
page.paste(img, (rect.x + OFFSET, rect.y + OFFSET))
page.save("export%sx%s_%s.jpeg" % (A4WIDTH, A4HEIGHT, INDEX))
INDEX += 1
print("Exported %s export%sx%s_*.jpeg files" % (INDEX -1, A4WIDTH, A4HEIGHT))
print("finished")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment