Sub topic 6
Resizing and Normalizing Images Before Sending
This chapter covers preparing images before you put them in a request. It assumes you can read files as bytes, have called an LLM chat API, and know that images consume tokens from the context window. Earlier chapters showed how to build an image content block and which formats and size limits apply. Here you will shrink and standardize images so requests stay small, cheap, and predictable.
Why preprocess at all
Most providers resize large images on their side. If you upload a 6000 by 4000 pixel photo, the provider scales it down before the model sees it. You still pay for the upload, and the request can hit a payload limit before any resizing happens. Some providers also charge input tokens based on the size of the image they receive, so oversized images can cost more than they help.
Preprocessing on your side gives you three things:
- Smaller payloads. Base64 text is about one third larger than the raw bytes. A smaller file means a faster upload and fewer rejected requests.
- Predictable cost. When you control the final dimensions, you can estimate the token cost ahead of time.
- Consistent input. Phone photos, screenshots, and scans arrive in different formats, orientations, and color modes. Normalizing them removes a class of surprises.
Preprocessing is not free of risk. Shrinking too far destroys small text and fine detail, which is the most common cause of wrong answers on charts and documents. The goal is the smallest image that still contains what the question needs.
The pipeline
A reliable preprocessing step does the same few operations in the same order every time.
Step 1: Apply EXIF orientation
Phones often store a photo sideways and add an EXIF tag (metadata inside the file) that says how to rotate it for display. Many viewers honor the tag. If you strip metadata later without rotating first, the model receives a sideways image and may read text poorly. Pillow's ImageOps.exif_transpose rotates the pixels according to the tag and removes the tag.
Step 2: Convert the color mode
Images can be RGB, RGBA (with transparency), grayscale, palette-based, or CMYK. JPEG cannot store transparency, so saving an RGBA image as JPEG raises an error. Converting to RGB is the usual fix. For transparent PNGs, paste the image onto a white background first. Otherwise transparent areas often become black, which can hide dark text.
Step 3: Downscale
Pillow's thumbnail method shrinks an image in place so that both sides fit inside a box. It keeps the aspect ratio and never enlarges. Use a high-quality resampling filter such as LANCZOS, which preserves edges better than the default for large reductions.
Step 4: Encode and check size
Choose the output format by content:
| Content | Better format | Reason |
|---|---|---|
| Photographs | JPEG | Small files, artifacts are hard to notice |
| Screenshots, charts, diagrams, text | PNG | Lossless, sharp edges stay sharp |
| Very large screenshots | PNG, then downscale | JPEG blurs thin lines and small text |
Then check the encoded byte count against the limit. If it is over, reduce quality or dimensions and try again.
A complete normalizer
The function below combines all four steps. It returns bytes and a media type, ready for the base64 helper from earlier chapters.
import io
from PIL import Image, ImageOps
MAX_SIDE = 1568
MAX_BYTES = 4_500_000 # stay under a typical 5 MB limit; check your provider
def flatten_to_rgb(img):
"""Convert any mode to RGB, placing transparency on a white background."""
if img.mode in ("RGBA", "LA") or (img.mode == "P" and "transparency" in img.info):
rgba = img.convert("RGBA")
background = Image.new("RGB", rgba.size, (255, 255, 255))
background.paste(rgba, mask=rgba.split()[-1])
return background
return img.convert("RGB")
def normalize_image(path, max_side=MAX_SIDE, max_bytes=MAX_BYTES, use_png=False):
"""Return (media_type, bytes) for a cleaned-up, size-limited image."""
with Image.open(path) as img:
img = ImageOps.exif_transpose(img)
img = flatten_to_rgb(img)
img.thumbnail((max_side, max_side), Image.Resampling.LANCZOS)
if use_png:
buffer = io.BytesIO()
img.save(buffer, format="PNG", optimize=True)
return "image/png", buffer.getvalue()
quality = 90
while True:
buffer = io.BytesIO()
img.save(buffer, format="JPEG", quality=quality)
if buffer.tell() <= max_bytes or quality <= 50:
return "image/jpeg", buffer.getvalue()
quality -= 10
media_type, raw = normalize_image("photo_large.png")
print(media_type, len(raw), "bytes")The JPEG loop stops at quality 50. Below that, artifacts usually damage legibility more than a smaller dimension would. If the file is still too big at quality 50, reduce max_side instead.
To send the result, encode the bytes yourself:
import base64
encoded = base64.standard_b64encode(raw).decode("utf-8")
block = {
"type": "image",
"source": {"type": "base64", "media_type": media_type, "data": encoded},
}
print(block["source"]["media_type"], len(encoded))Choosing the maximum side
There is no single correct value. The right size depends on how much detail the question needs.
- Scene description or object recognition: 768 to 1024 pixels on the long side is often enough.
- Reading charts and labels: use the provider's recommended maximum, because axis labels and legends are small.
- Dense documents and tables: keep full resolution up to the limit, or split the image into tiles (see below).
A useful test is to view your downscaled output yourself. If you cannot read the text you care about, the model probably cannot either.
Handling very large or very tall images
A long screenshot, such as a full web page that is 1200 pixels wide and 9000 tall, shrinks badly when you force it into a square box. Text becomes unreadable. Cutting it into overlapping horizontal strips keeps each strip legible.
from PIL import Image
def split_tall_image(img, tile_height=1400, overlap=100):
"""Yield horizontal strips of a tall image with a small overlap."""
width, height = img.size
top = 0
while top < height:
bottom = min(top + tile_height, height)
yield img.crop((0, top, width, bottom))
if bottom == height:
break
top = bottom - overlap
tall = Image.new("RGB", (1200, 4000), "white")
strips = list(split_tall_image(tall))
print(len(strips), "strips")The overlap prevents a line of text from being cut in half at a boundary. When you send several strips, tell the model they are consecutive parts of one image and keep them in order. Chapter on multiple images covers prompt placement.
Common errors
- Sideways images. Caused by skipping EXIF handling. Call
exif_transposebefore anything else. OSError: cannot write mode RGBA as JPEG. Convert to RGB first, asflatten_to_rgbdoes.- Black backgrounds on transparent PNGs. Paste onto white instead of a plain mode conversion.
- Unreadable text after resizing. The maximum side is too small, or JPEG compression blurred thin strokes. Raise the size or switch to PNG.
- Mismatched media type. If you re-encode to JPEG, send
image/jpeg, not the original file's type. Take the media type from your encoder, not from the input filename. - Request still too large. Remember that base64 adds about 33 percent. A 4.5 MB file becomes roughly 6 MB of text.
Privacy note on metadata
Photos often carry GPS coordinates, device names, and timestamps in EXIF. Re-saving through Pillow as shown here does not copy most of that metadata to the output, which is a useful side effect. Do not rely on this as your only privacy control. Later chapters cover handling sensitive images properly.
Exercise
A user uploads a phone photo of a receipt. The model reports the text is upside down, and your code raises an error when saving a screenshot with a transparent background as JPEG. Which two preprocessing steps fix these problems, and why does the order matter for the first one?
Show answer
Apply EXIF orientation with ImageOps.exif_transpose, and convert the image to RGB (flattening transparency onto a white background) before saving as JPEG. Orientation must be applied before any step that drops metadata, because once the EXIF tag is lost the rotation information is gone and the pixels stay sideways.
Exercise
You downscale a 3000 by 2000 PNG chart to a maximum side of 512 pixels and save it as JPEG at quality 60. The model now misreads the axis labels. Name two changes you could make and what each one trades off.
Show answer
Raise the maximum side toward the provider's recommended size, which increases file size and token cost. Or save as PNG instead of JPEG, which keeps thin lines and small text sharp but produces a larger file. Both keep the labels legible at the price of a bigger, costlier request.