
With Pillow, opening an image and choosing how to work with it are separate decisions. Image.open() reads enough metadata to identify the file, but pixel data is usually loaded only when needed. Convert the image to a predictable mode before applying operations that assume a particular number of channels.
from PIL import Image
with Image.open("input.jpg") as source:
image = source.convert("RGB")
For ordinary color photographs, RGB is a useful working mode: every pixel has red, green, and blue channels. A JPEG may already use that mode, but a PNG can be grayscale, palette-based, or contain transparency. Converting explicitly makes later code less dependent on the input file.
If transparency matters, use RGBA rather than discarding the alpha channel. That is especially important for logos, icons, and images with transparent backgrounds.
from PIL import Image
with Image.open("overlay.png") as source:
image = source.convert("RGBA")
For operations on brightness or masks, a single-channel grayscale image is often the clearest representation. Pillow names this mode L.
from PIL import Image
with Image.open("input.png") as source:
grayscale = source.convert("L")
Some files store pixels in a palette mode, where each pixel is an index into a color table. Converting before pixel-level work avoids treating those indexes as colors. For photographic edits, convert to RGB or RGBA; for a grayscale mask, convert to L.
Images from cameras may also carry orientation in EXIF metadata. Apply that orientation when loading so the pixel dimensions and displayed direction agree.
from PIL import Image, ImageOps
with Image.open("camera-photo.jpg") as source:
oriented = ImageOps.exif_transpose(source)
image = oriented.convert("RGB")
Keep the file open while the image is being loaded or copied, and make the working image independent of the file handle when it needs to outlive the context manager.
from PIL import Image
with Image.open("input.png") as source:
image = source.convert("RGBA").copy()
Applying point operations and color adjustments
A point operation replaces each pixel value with a value calculated from that pixel alone. It does not use neighboring pixels, so it can change brightness, apply a threshold, or remap individual color channels without changing the image dimensions.
For an 8-bit grayscale image, Image.point() applies a function to every value from 0 through 255. Pillow clips results to the valid range.
from PIL import Image
with Image.open("input.jpg") as source:
grayscale = source.convert("L")
brighter = grayscale.point(lambda value: value + 30)
A lookup table makes the mapping explicit and can be reused across images. Here, values below the threshold become black, and values at or above it become white.
from PIL import Image
threshold = 128
table = [0 if value < threshold else 255 for value in range(256)]
with Image.open("input.jpg") as source:
grayscale = source.convert("L")
binary = grayscale.point(table)
A gamma adjustment is another lookup-table operation. The formula below brightens values when gamma is less than one and darkens them when it is greater than one. Clamping the input to the range from zero to one keeps the calculation valid.
from PIL import Image
gamma = 0.8
table = [
round(((value / 255) ** gamma) * 255)
for value in range(256)
]
with Image.open("input.jpg") as source:
grayscale = source.convert("L")
adjusted = grayscale.point(table)
For color images, split the channels when each needs a different mapping. This example scales red and blue independently while leaving green unchanged.
from PIL import Image
def scale_table(factor):
return [
min(255, round(value * factor))
for value in range(256)
]
with Image.open("input.jpg") as source:
red, green, blue = source.convert("RGB").split()
red = red.point(scale_table(1.1))
blue = blue.point(scale_table(0.9))
adjusted = Image.merge("RGB", (red, green, blue))
When working with transparency, transform only the color channels if the alpha values must remain intact. Applying the same operation to alpha can change the image’s opacity as well as its appearance.
from PIL import Image
def scale_table(factor):
return [
min(255, round(value * factor))
for value in range(256)
]
with Image.open("overlay.png") as source:
red, green, blue, alpha = source.convert("RGBA").split()
red = red.point(scale_table(1.1))
green = green.point(scale_table(1.1))
blue = blue.point(scale_table(1.1))
adjusted = Image.merge("RGBA", (red, green, blue, alpha))
A point operation is appropriate when each output value depends only on the corresponding input value. Operations that depend on nearby pixels, such as sharpening or blurring, need a different kind of filter.
Building reusable filters with image enhancement
Pillow’s ImageEnhance classes provide reusable adjustments for brightness, contrast, color, and sharpness. Each accepts a factor: 1.0 leaves the image unchanged, values below 1.0 reduce the effect, and values above 1.0 increase it.
from PIL import Image, ImageEnhance
with Image.open("input.jpg") as source:
image = source.convert("RGB")
brighter = ImageEnhance.Brightness(image).enhance(1.2)
more_contrast = ImageEnhance.Contrast(brighter).enhance(1.15)
Enhancements can be applied in sequence, but their order matters. Increasing contrast after brightness does not generally produce the same pixels as increasing brightness after contrast. Keeping the sequence explicit makes the result easier to reproduce and adjust.
A small function can collect the choices that define a filter. Returning a new image instead of modifying a shared input makes the function safe to reuse in different processing paths.
from PIL import ImageEnhance
def enhance_image(
image,
brightness=1.0,
contrast=1.0,
color=1.0,
sharpness=1.0,
):
result = image.copy()
for enhancer, factor in (
(ImageEnhance.Brightness, brightness),
(ImageEnhance.Contrast, contrast),
(ImageEnhance.Color, color),
(ImageEnhance.Sharpness, sharpness),
):
if factor != 1.0:
result = enhancer(result).enhance(factor)
return result
Because the function accepts an image rather than a filename, it can be used with images already loaded, cropped, or resized. The same parameter set can be applied consistently to a batch.
from pathlib import Path
from PIL import Image
settings = {
"brightness": 1.08,
"contrast": 1.12,
"color": 0.9,
"sharpness": 1.1,
}
for path in Path("photos").glob("*.jpg"):
with Image.open(path) as source:
image = enhance_image(source.convert("RGB"), **settings)
image.save(Path("edited") / path.name)
For an image with transparency, apply the enhancements to its color channels and restore the original alpha channel afterward. This keeps the filter from changing which pixels are transparent or partially transparent.
from PIL import Image
def enhance_rgba(image, **settings):
rgba = image.convert("RGBA")
red, green, blue, alpha = rgba.split()
rgb = Image.merge("RGB", (red, green, blue))
enhanced = enhance_image(rgb, **settings)
enhanced.putalpha(alpha)
return enhanced
Enhancement factors are parameters, not universal measures of visual strength. A factor that works for one image may be too strong for another, so storing the settings alongside a batch or preset makes the processing reproducible.
Combining effects through compositing and masks
Compositing combines images pixel by pixel. For two images with transparency, Image.alpha_composite() uses their alpha channels to place the foreground over the background. The images must have the same size and use RGBA mode.
from PIL import Image
with Image.open("background.jpg") as source:
background = source.convert("RGBA")
with Image.open("overlay.png") as source:
overlay = source.convert("RGBA")
if overlay.size != background.size:
overlay = overlay.resize(background.size)
result = Image.alpha_composite(background, overlay)
To place an overlay at a particular position, create a transparent canvas the size of the background and paste the overlay onto it. Passing the overlay as the paste mask preserves its transparency in the positioned layer.
from PIL import Image
with Image.open("background.jpg") as source:
background = source.convert("RGBA")
with Image.open("logo.png") as source:
logo = source.convert("RGBA")
layer = Image.new("RGBA", background.size, (0, 0, 0, 0))
layer.paste(logo, (24, 24), logo)
result = Image.alpha_composite(background, layer)
A mask controls how much of each source pixel contributes to a composite. In an L mask, black selects the first image, white selects the second, and gray values blend between them. The mask must match the images’ dimensions.
from PIL import Image
with Image.open("original.jpg") as source:
original = source.convert("RGB")
with Image.open("treatment.jpg") as source:
treatment = source.convert("RGB").resize(original.size)
with Image.open("mask.png") as source:
mask = source.convert("L").resize(original.size)
result = Image.composite(treatment, original, mask)
The order of the image arguments is significant: where the mask is white, Image.composite() selects the first image; where it is black, it selects the second. This makes a mask useful for applying a color or contrast treatment only to a selected region.
Blurring a mask softens its boundary. The image blend then changes gradually across that edge instead of forming a hard transition.
from PIL import Image, ImageFilter
with Image.open("original.jpg") as source:
original = source.convert("RGB")
treatment = original.filter(ImageFilter.GaussianBlur(radius=8))
mask = Image.new("L", original.size, 0)
mask_draw = Image.new("L", original.size, 0)
from PIL import ImageDraw
draw = ImageDraw.Draw(mask_draw)
draw.ellipse((80, 60, 420, 400), fill=255)
mask = mask_draw.filter(ImageFilter.GaussianBlur(radius=24))
result = Image.composite(treatment, original, mask)
For a mask derived from image content, convert a channel or a grayscale version of the image to L, then adjust its levels with a point table. The resulting mask can select bright areas more strongly than dark ones.
from PIL import Image
with Image.open("input.jpg") as source:
image = source.convert("RGB")
gray = image.convert("L")
mask = gray.point([
0 if value < 96 else min(255, (value - 96) * 2)
for value in range(256)
])
treatment = image.filter(ImageFilter.GaussianBlur(radius=4))
result = Image.composite(treatment, image, mask)
When the source has an alpha channel, keep the mask’s role distinct from the image alpha. A composite mask chooses between images, while alpha describes how opaque a pixel is when the result is placed over another image.
Saving results with predictable formats and quality
Choose the output format deliberately. JPEG is usually appropriate for photographs, but it does not preserve transparency and applies lossy compression. PNG preserves pixels and alpha without loss, which makes it a better fit for graphics, masks, and images with transparent areas.
Set the format and JPEG options explicitly rather than relying on defaults. A quality value around 85 is a useful starting point for photographs; higher values retain more detail at the cost of larger files. A quality setting of 100 still does not make JPEG lossless.
from PIL import Image
with Image.open("input.jpg") as source:
image = source.convert("RGB")
image.save(
"output.jpg",
format="JPEG",
quality=85,
optimize=True,
progressive=True,
)
JPEG cannot store an alpha channel. If the source contains transparency, decide what should appear behind it before converting to RGB. Compositing against a chosen background avoids relying on an implicit conversion of transparent pixels.
from PIL import Image
with Image.open("overlay.png") as source:
foreground = source.convert("RGBA")
background = Image.new("RGBA", foreground.size, (255, 255, 255, 255))
flattened = Image.alpha_composite(background, foreground).convert("RGB")
flattened.save(
"output.jpg",
format="JPEG",
quality=88,
optimize=True,
)
For PNG, compression settings affect file size and encoding time, not image quality. The compress_level value ranges from 0, which favors speed, to 9, which favors smaller files.
from PIL import Image
with Image.open("input.png") as source:
image = source.convert("RGBA")
image.save(
"output.png",
format="PNG",
optimize=True,
compress_level=6,
)
Make the output mode match the intended content. Converting a palette image to RGBA preserves transparency while making the channel layout explicit; converting a photograph to RGB prevents an accidental alpha channel from reaching a format that cannot store it.
Metadata is a separate choice from pixel encoding. Pillow does not preserve every piece of source metadata automatically in every save operation. When a color-managed workflow needs the embedded ICC profile, pass it through explicitly.
from PIL import Image
with Image.open("input.jpg") as source:
image = source.convert("RGB")
icc_profile = source.info.get("icc_profile")
save_options = {
"format": "JPEG",
"quality": 88,
"optimize": True,
}
if icc_profile:
save_options["icc_profile"] = icc_profile
image.save("output.jpg", **save_options)
EXIF data can also be supplied explicitly when it should be retained. If the image was reoriented with ImageOps.exif_transpose(), check the orientation tag before copying metadata so a viewer does not rotate the already-oriented pixels a second time.
from PIL import Image, ImageOps
with Image.open("camera.jpg") as source:
image = ImageOps.exif_transpose(source).convert("RGB")
exif = source.getexif()
exif.pop(274, None)
image.save(
"output.jpg",
format="JPEG",
quality=88,
exif=exif,
)
Use a temporary path when a partially written file must not appear under the final name. Saving completes before the rename, so readers that look for the destination do not encounter an incomplete output.
from pathlib import Path
from PIL import Image
destination = Path("edited/output.jpg")
temporary = destination.with_suffix(".tmp.jpg")
with Image.open("input.jpg") as source:
image = source.convert("RGB")
image.save(
temporary,
format="JPEG",
quality=88,
optimize=True,
)
temporary.replace(destination)
For batch processing, create the output directory and choose the format from the intended result rather than merely reusing the input extension. A PNG input saved as JPEG needs an explicit transparency decision, while a JPEG saved as PNG will not recover detail lost to earlier compression.
from pathlib import Path
from PIL import Image
input_dir = Path("photos")
output_dir = Path("rendered")
output_dir.mkdir(parents=True, exist_ok=True)
for path in input_dir.glob("*.jpg"):
with Image.open(path) as source:
image = source.convert("RGB")
destination = output_dir / f"{path.stem}.jpg"
image.save(
destination,
format="JPEG",
quality=88,
optimize=True,
progressive=True,
)

