Skip to content

Instantly share code, notes, and snippets.

@tonyroberts
Created November 29, 2019 15:46
Show Gist options
  • Save tonyroberts/5e2bf5321ce61b90043a310b617d744a to your computer and use it in GitHub Desktop.
Save tonyroberts/5e2bf5321ce61b90043a310b617d744a to your computer and use it in GitHub Desktop.
from pyxll import xl_app, async_call
import win32gui, win32ui
import tempfile
import os
def get_image_size(image):
"""Return the size of an image in pixels as (width, height)."""
# Get the size of the input image in pixels (Excel sizes are in points,
# or 1/72th of an inch.
xl = xl_app()
dc = win32gui.GetDC(xl.Hwnd)
pixels_per_inch_x = win32ui.GetDeviceCaps(dc, win32con.LOGPIXELSX)
pixels_per_inch_y = win32ui.GetDeviceCaps(dc, win32con.LOGPIXELSY)
size_x = int(image.Width * pixels_per_inch_x / 72)
size_y = int(image.Height * pixels_per_inch_y / 72)
return size_x, size_y
def create_temporary_file(suffix=None):
"""Create a named temporary file that is deleted automatically."""
# Rather than delete the file when it's closed we delete it when the
# windows message loop next runs. This gives Excel enough time to
# load the image before the file disappears.
file = tempfile.NamedTemporaryFile(suffix=suffix, delete=False)
def try_delete(filename):
try:
os.unlink(filename)
except PermissionError:
# retry if Excel is still accessing it
async_call(os.unlink, filename)
# Make sure the file gets deleted after the function is complete
async_call(try_delete, file.name)
return file
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment