Ask Anvil

Answers to questions about automating PDFs, e-signatures, Webforms, and other paperwork problems.
E-signatures
Categories

Why does my signature image turn black or raise an error when I convert it to JPEG in Python, and how do I fix it?

The problem

You capture a drawn signature as a transparent PNG, then try to save it as a JPEG before stamping it onto a PDF. One of two things happens: Pillow raises an error, or you work around the error and the signature appears on a black rectangle.

The cause

JPEG has no alpha channel. Saving an RGBA image directly raises OSError: cannot write mode RGBA as JPEG (confirmed on Pillow 12.3.0). The usual workaround, img.convert("RGB"), simply drops the alpha channel without blending it. Fully transparent pixels then show whatever RGB values they stored, which in my test file was black, so the background came out black.

The fix

Paste the signature onto a white canvas using its own alpha, then convert and save.

from PIL import Image

sig = Image.open("signature.png")  # RGBA PNG with a transparent background
white = Image.new("RGBA", sig.size, (255, 255, 255, 255))
flat = Image.alpha_composite(white, sig.convert("RGBA")).convert("RGB")
flat.save("signature.jpg", quality=95)

In my test, the corner pixel of the naive convert("RGB") result was (0, 0, 0), and the corner pixel after compositing was (255, 255, 255).

Caveats

If your PDF library accepts PNG with transparency, skip JPEG entirely and keep the PNG, since it preserves the transparent background. Compositing onto white only looks right on a white page, so change the canvas color if the signature sits on a tinted field. JPEG is also lossy, which can leave faint artifacts around thin pen strokes, so keep the quality high.

Back to All Questions

The fastest way to build software for documents

Anvil Document SDK is a comprehensive toolbox for product teams launching document flows where PDF filling, signing, and complex conditional scenarios are necessary.
Explore Anvil
Anvil Webforms
Marketing Mode