Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import os
- from PIL import Image, ImageFont, ImageDraw
- proof_target_ratio = (4, 3) #desired aspect ratio, images will be cropped to fit
- proof_big = (4000, 4000) #max resulting image size
- proof_small_width = 490 #proof width
- proof_caption_height = 40 #caption height (can be 0)
- proof_box = 5 #border size (can be 0)
- proof_bgcolor = (255, 255, 255) #rgb background color
- proof_textcolor = (0, 0, 0) #rgb caption color
- proof_font = "timesbd.ttf" #caption font file
- proof_font_size = 36 #caption font size
- caption_filename = "captions.txt" #captions file
- proof_small_height = int(proof_small_width / proof_target_ratio[0] * proof_target_ratio[1])
- im_big = Image.new("RGB", proof_big, proof_bgcolor)
- proof_target = proof_target_ratio[0] / proof_target_ratio[1]
- xpos = 0
- ypos = 0
- count = 0
- caption_file = open(caption_filename, "r")
- caption_font = ImageFont.truetype(proof_font, proof_font_size)
- for infile in sorted(os.listdir('.')):
- f, e = os.path.splitext(infile)
- if f == "proof":
- continue
- print("Opening ", infile)
- try:
- proof = Image.open(infile)
- except IOError:
- print(infile, "does not seem to be an image file")
- continue
- if proof.size[0] / proof.size[1] != proof_target:
- if proof.size[0] > proof.size[1]:
- new_width = int(proof.size[1] * proof_target)
- new_height = proof.size[1]
- box = ( int((proof.size[0] - new_width)/2), 0, int((proof.size[0] - new_width)/2 + new_width), proof.size[1] )
- else:
- new_width = proof.size[0]
- new_height = int(proof.size[0] / proof_target)
- box = ( 0, int((proof.size[1] - new_height) / 2), proof.size[0], int((proof.size[1] - new_height) / 2 + new_height) )
- proof = proof.crop(box)
- proof = proof.resize( (proof_small_width, proof_small_height), Image.LANCZOS )
- im_big.paste(proof, (xpos + proof_box, ypos) )
- text = caption_file.readline().strip()
- cap_size = caption_font.getsize(text)
- while cap_size[0] > proof_small_width:
- text = text[:-1]
- cap_size = caption_font.getsize(text)
- align = (proof_small_width - cap_size[0]) / 2
- topleft = (xpos + align, ypos + proof_small_height + 2)
- print("Putting text to ", topleft)
- print(text)
- caption_draw = ImageDraw.Draw(im_big)
- caption_draw.text(topleft, text, fill=proof_textcolor, font=caption_font)
- count = count + 1
- xpos = xpos + proof_small_width + 2*proof_box
- if xpos + proof_small_width >= proof_big[0]:
- xpos = 0
- ypos = ypos + proof_small_height + proof_caption_height
- if ypos >= proof_big[1]:
- break
- print(count, "images processed, cropping")
- im_big = im_big.crop( (0, 0, 4000, ypos + proof_small_height + proof_caption_height))
- print("Saving")
- im_big.save("proof.jpg", "jpeg", quality=95)
- print("Done")
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement