-
-
Save rdapaz/bf78696cce2eb61e75bf056ac4235912 to your computer and use it in GitHub Desktop.
add an image in every Powerpoint slide using python-pptx
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import pptx | |
import os | |
import re | |
import exifread | |
import time | |
import pprint | |
from pptx.util import Cm | |
from PIL import Image | |
from random import shuffle | |
OUTPUT_TAG = "NameHere" | |
DEBUG = False | |
if not DEBUG: | |
# new | |
prs = pptx.Presentation() | |
# open | |
# prs_exists = pptx.Presentation("some_presentation.pptx") | |
# default slide width | |
#prs.slide_width = 9144000 | |
# slide height @ 4:3 | |
#prs.slide_height = 6858000 | |
# slide height @ 16:9 | |
prs.slide_height = 5143500 | |
# title slide | |
slide = prs.slides.add_slide(prs.slide_layouts[0]) | |
# blank slide | |
#slide = prs.slides.add_slide(prs.slide_layouts[6]) | |
# set title | |
title = slide.shapes.title | |
title.text = "Lauren's & Tahlia's 18th Birthday Party" | |
pic_left = int(prs.slide_width * 0.15) | |
pic_top = int(prs.slide_height * 0.05) | |
pic_width = int(prs.slide_width * 0.7) | |
rootdir = r'C:\Users\rdapaz.DESKTOP-QSI65RE\Desktop\Pictures' | |
def pretty_printer(o): | |
pp = pprint.PrettyPrinter(indent=4) | |
pp.pprint(o) | |
def exif_info2time(ts): | |
"""changes EXIF date ('2005:10:20 23:22:28') to number of seconds since 1970-01-01""" | |
tpl = time.strptime(ts + 'UTC', '%Y:%m:%d %H:%M:%S%Z') | |
return time.mktime(tpl) | |
def get_exif_date(img): | |
tags = exifread.process_file(img) | |
# pretty_printer(tags) | |
dt = None | |
if tags: | |
all_dt_tags = [x for x in tags if re.search(r'(date|time)', x, re.IGNORECASE)] | |
if all_dt_tags: | |
tag = all_dt_tags[0] | |
dt = '%s' % tags[tag] | |
return dt | |
images = [] | |
for subdir, dirs, files in os.walk(rootdir): | |
for my_file in files: | |
if re.search(r'(jpg)$', my_file, re.IGNORECASE): | |
filename = os.path.join(subdir, my_file) | |
images.append(filename) | |
shuffle(images) | |
count = 0 | |
failures = [] | |
if not DEBUG: | |
for filename in images: | |
count += 1 | |
print(f'[{str(count).zfill(3)}] Processing {filename}...') | |
with open(filename, 'rb') as fin: | |
img = Image.open(fin) | |
try: | |
slide = prs.slides.add_slide(prs.slide_layouts[6]) | |
if img.height > img.width: | |
pic = slide.shapes.add_picture(filename, pic_left, pic_top, height=Cm(9.01)) | |
else: | |
pic = slide.shapes.add_picture(filename, pic_left, pic_top, height=Cm(11.43)) | |
except: | |
failures.append(filename) | |
if not DEBUG: | |
prs.save("%s.pptx" % OUTPUT_TAG) | |
for file in failures: | |
print(file) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment