Skip to content

Instantly share code, notes, and snippets.

@kms70847
Created September 19, 2019 12:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kms70847/e554706db1269d005730ca6868b88eb8 to your computer and use it in GitHub Desktop.
Save kms70847/e554706db1269d005730ca6868b88eb8 to your computer and use it in GitHub Desktop.
makegrid.py - copy rectangular grids to the clipboard
from PIL import Image, ImageDraw
import sys
from io import BytesIO
from ctypes import memmove, windll, c_size_t as SIZE_T
from ctypes.wintypes import UINT, LPVOID, BOOL, HWND, HANDLE
HGLOBAL = HANDLE
GHND = 0x0042
GMEM_SHARE = 0x2000
GlobalAlloc = windll.kernel32.GlobalAlloc
GlobalAlloc.restype = HGLOBAL
GlobalAlloc.argtypes = [UINT, SIZE_T]
GlobalLock = windll.kernel32.GlobalLock
GlobalLock.restype = LPVOID
GlobalLock.argtypes = [HGLOBAL]
GlobalUnlock = windll.kernel32.GlobalUnlock
GlobalUnlock.restype = BOOL
GlobalUnlock.argtypes = [HGLOBAL]
CF_DIB = 8
OpenClipboard = windll.user32.OpenClipboard
OpenClipboard.restype = BOOL
OpenClipboard.argtypes = [HWND]
EmptyClipboard = windll.user32.EmptyClipboard
EmptyClipboard.restype = BOOL
EmptyClipboard.argtypes = None
SetClipboardData = windll.user32.SetClipboardData
SetClipboardData.restype = HANDLE
SetClipboardData.argtypes = [UINT, HANDLE]
CloseClipboard = windll.user32.CloseClipboard
CloseClipboard.restype = BOOL
CloseClipboard.argtypes = None
def copy_to_clipboard(image):
output = BytesIO()
image.convert("RGB").save(output, "BMP")
data = output.getvalue()[14:]
output.close()
hData = GlobalAlloc(GHND | GMEM_SHARE, len(data))
pData = GlobalLock(hData)
memmove(pData, data, len(data))
GlobalUnlock(hData)
OpenClipboard(None)
EmptyClipboard()
SetClipboardData(CF_DIB, pData)
CloseClipboard()
def make_grid(num_cols, num_rows, col_width, row_height, background="white", line_color="black"):
height = 1 + row_height*num_rows
width = 1 + col_width*num_cols
img = Image.new("RGB", (width, height), background)
draw = ImageDraw.Draw(img)
for i in range(num_cols+1):
x = i * col_width
draw.line((x, 0, x, height), fill=line_color)
for j in range(num_rows+1):
y = j * row_height
draw.line((0, y, width, y), fill=line_color)
return img
if len(sys.argv) < 5:
print("Usage: makeGrid COLS ROWS CELLWIDTH CELLHEIGHT [BACKGROUNDCOLOR] [LINECOLOR]")
exit(0)
_, *args = [int(s) if s.isdigit() else s for s in sys.argv]
copy_to_clipboard(make_grid(*args))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment