-
-
Notifications
You must be signed in to change notification settings - Fork 2.4k
Open
Labels
Description
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:
- This will eagerly trigger
load()which may not be necessary if we end up not using the image's bytes - 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.