Skip to content

Instantly share code, notes, and snippets.

@scanny
Created October 4, 2013 22:32
Show Gist options
  • Save scanny/6833945 to your computer and use it in GitHub Desktop.
Save scanny/6833945 to your computer and use it in GitHub Desktop.
Some working code that adjusts the size of an image placed in python-pptx based on it's stated DPI, overriding the default DPI python-pptx v0.2.6 uses.
#
# forces python-pptx to display images at native size, based on DPI attribute
# in image file, from Chad ...
#
import Image
import Presentation
from pptx.util import Inches
left = Inches(0.83)
top = Inches(2.4)
prs = Presentation()
slide = prs.slides.add_slide(prs.slidelayouts[5])
slide.shapes.title.text = 'Adding a High-res Image'
img = Image.open('filename.png')
#I had to float these, otherwise, integer division occurred
pixelWidth = float(img.size[0])
piexelHeight = float(img.size[1])
dpi = float(img.info['dpi'])
imageWidth = Inches(pixelWidth/dpi)
imageHeight = Inches(pixelHeight/dpi)
slide.shapes.add_picture('filename.png', left, top, imageWidth, imageHeight)
# My images come from a very stable, predictable source: matplotlib,
# where I have that package write out a .png file (dpi can vary). I found that
# these .png files always carried the dpi info, so I didn't think to put in
# the exception language that you did.
#
# This code works very reliably for me so far.
# another rough idea, not tested:
image = Image.open('my_image.png')
try:
dpi_tuple = image.info['dpi'] # apparently not all files have this attribute
# return value will look something like (96, 96) as I understand it
dpi = dpi_tuple[0] # assuming it's not scaled differently on x and y axes
except KeyError:
dpi = 72 if platform.system() == 'darwin' else 96
emus_per_px = int(914400/dpi)
width = image.size[0] * emus_per_px
height = image.size[1] * emus_per_px
slide.shapes.add_picture('my_image.png', left, top, width, height)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment