Skip to content

Add option to skip load() and copy() if .convert(...) is not required #9298

@bromano-oai

Description

@bromano-oai

Background

We frequently want to ensure that a given image is in "RGB" mode. To that end, frequently in code .convert("RGB") is invoked immediately after opening an image with Image.open(...).

However, this is wasteful in two ways:

  1. This will eagerly trigger load() which may not be necessary if we end up not using the image's bytes
  2. This will trigger .copy() where in many cases, a new image is not strictly needed or desired.
    def convert(
        self,
        mode: str | None = None,
        matrix: tuple[float, ...] | None = None,
        dither: Dither | None = None,
        palette: Palette = Palette.WEB,
        colors: int = 256,
    ) -> Image:
        self.load()

        has_transparency = "transparency" in self.info
        if not mode and self.mode == "P":
            # determine default mode
            if self.palette:
                mode = self.palette.mode
            else:
                mode = "RGB"
            if mode == "RGB" and has_transparency:
                mode = "RGBA"
        if not mode or (mode == self.mode and not matrix):
            return self.copy()

Workaround

This can be mitigated by doing conditional check for conversion, but this is a bit verbose.

img = Image.open(...)
if img.mode == "RGB":
  img = img.convert("RGB")

Ask
Is there an opportunity to create an alternative API that can ensure the image is in the right mode and perform load() and copy() only when strictly necessary.

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions