Skip to content

Instantly share code, notes, and snippets.

@AceofSpades5757
Last active April 12, 2024 04:17
Show Gist options
  • Save AceofSpades5757/fb3e662b833e5bbc62341a840d3a2a40 to your computer and use it in GitHub Desktop.
Save AceofSpades5757/fb3e662b833e5bbc62341a840d3a2a40 to your computer and use it in GitHub Desktop.
Add a background to a PNG file
#!/usr/bin/env pip-run
"""Takes a PNG file, adds a white background to it, and copies it to the
clipboard.
Uses `pip-run` to run the script with the required packages installed.
This script is licensed under the MIT License.
Copyright © 2024 Kyle L. Davis
"""
__requires__ = ["Pillow", "pywin32"]
import io
import sys
from pathlib import Path
from typing import TypeAlias
from typing import Union
import win32clipboard
from PIL import Image
PathLike = Union[str, bytes, Path]
RGBA: TypeAlias = tuple[int, int, int, int]
def add_white_bg_to_png(
png_file: PathLike,
copy: bool = True,
open: bool = False,
background_color: RGBA = (255, 255, 255, 255),
) -> None:
"""Add a white background to a PNG file and copy it to the clipboard."""
with Image.open(png_file) as img:
img = img.convert("RGBA")
bg = Image.new("RGBA", img.size, background_color)
img = Image.alpha_composite(bg, img)
# Copy to clipboard
if copy:
output = io.BytesIO()
img.convert("RGB").save(output, "BMP")
data = output.getvalue()[14:]
output.close()
win32clipboard.OpenClipboard()
win32clipboard.EmptyClipboard()
win32clipboard.SetClipboardData(win32clipboard.CF_DIB, data)
win32clipboard.CloseClipboard()
# Open the image
if open:
img.show()
print("Image copied to clipboard.")
if __name__ == "__main__":
if len(sys.argv) != 2:
print(f"Usage: {sys.argv[0]} <png_file>")
print(
"Takes a PNG file and adds a white background to it, copying it to the clipboard."
)
raise SystemExit(1)
add_white_bg_to_png(sys.argv[1])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment