Skip to content

Pixmap export 'unmultiply' option has no effect #5115

Description

@BenVosper

Description of the bug

Pixmap.pil_save and Pixmap.pil_tobytes docs both mention an unmultiply kwarg that seems to have no effect.

I noticed this when trying to do pil_save as webp using the example from the docs. By default the images this creates have the premultiplied alpha and toggling this kwarg doesn't change anything.

Let me know if I'm missing something. Thanks!

How to reproduce the bug

import inspect
from io import BytesIO

import pymupdf
from PIL import Image

print(f"PyMuPDF {pymupdf.__version__}")
print(f"pil_save{inspect.signature(pymupdf.Pixmap.pil_save)}")
print(f"pil_tobytes{inspect.signature(pymupdf.Pixmap.pil_tobytes)}")

# One page, one 50%-opacity red rectangle.
doc = pymupdf.open()
page = doc.new_page(width=100, height=100)
page.draw_rect(pymupdf.Rect(20, 20, 80, 80), fill=(1, 0, 0), fill_opacity=0.5)
pix = page.get_pixmap(alpha=True)

default = pix.pil_tobytes("PNG")
unmultiplied = pix.pil_tobytes("PNG", unmultiply=True)
print(f"\nunmultiply=True changes the output: {default != unmultiplied}")

pixel = (50, 50)
print(f"pixel {pixel}, premultiplied samples:         {pix.pixel(*pixel)}")
print(f"pixel {pixel}, pil_tobytes(unmultiply=True):  {Image.open(BytesIO(unmultiplied)).getpixel(pixel)}")
print(f"pixel {pixel}, Pixmap.tobytes('png'):         {Image.open(BytesIO(pix.tobytes("png"))).getpixel(pixel)}")

# Red at any opacity should read back as (255, 0, 0, a).
# pil_tobytes returns (a, 0, 0, a): the premultiplied samples, unchanged.

Running this prints:

PyMuPDF 1.28.2
pil_save(self, *args, **kwargs)
pil_tobytes(self, *args, **kwargs)

unmultiply=True changes the output: False
pixel (50, 50), premultiplied samples:         (126, 0, 0, 126)
pixel (50, 50), pil_tobytes(unmultiply=True):  (126, 0, 0, 126)
pixel (50, 50), Pixmap.tobytes('png'):         (255, 0, 0, 126)

PyMuPDF version

1.28.2

Operating system

Linux

Python version

3.13

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions