◉GEMINI LABJP
●OMNI 1.2 — Gemini Omni 1.2 Flash is generally available (11/5) with up to 15-second video and conversational editing; 1.1 Flash is routed to 1.2 on 12/3●COMPUTER — Computer Use is now generally available in the Interactions and GenerateContent APIs (10/30)●LIVE — Live and TTS preview models shut down as early as 11/17 (7 days left). Move to gemini-3.8-live and the 3.8 TTS models●CLI — Gemini API CLI (gemini-api) is out in beta (10/27): a zero-dependency client for agents and CI●2.5 PRO — gemini-2.5-pro and 2.5-flash are routed automatically on 12/1 (21 days left), to 3.8 Flash and 3.5 Flash-Lite●NEW — Stop Re-Reading Every Crash Report: Gre…●OMNI 1.2 — Gemini Omni 1.2 Flash is generally available (11/5) with up to 15-second video and conversational editing; 1.1 Flash is routed to 1.2 on 12/3●COMPUTER — Computer Use is now generally available in the Interactions and GenerateContent APIs (10/30)●LIVE — Live and TTS preview models shut down as early as 11/17 (7 days left). Move to gemini-3.8-live and the 3.8 TTS models●CLI — Gemini API CLI (gemini-api) is out in beta (10/27): a zero-dependency client for agents and CI●2.5 PRO — gemini-2.5-pro and 2.5-flash are routed automatically on 12/1 (21 days left), to 3.8 Flash and 3.5 Flash-Lite●NEW — Stop Re-Reading Every Crash Report: Gre…
Articles/API / SDK
◈ API / SDK/2026-05-09Intermediate

Why I Always Resize Images With Pillow Before Sending Them to the Gemini API

Sending raw iPhone photos to the Gemini API inflates both latency and tokens. This walks through the tile math from Google's docs, a Pillow helper that resizes before upload, and how to confirm the savings with count_tokens.

gemini-api291multimodal45python113pillowcost-optimization30

For a few months I uploaded iPhone photos straight from disk to the Gemini API in a small product-cataloging side project. Every request took eight to twelve seconds, and I told myself that was just what vision models cost.

When I finally opened usage_metadata, a single image was consuming an order of magnitude more tokens than a text-only request. Once I started shrinking the longest edge to 1024px before sending, responses came back in two to three seconds on my setup. Those timings are from my own project, not a benchmark.

This article retraces why, starting from how Google's documentation counts images, and shows the helper I settled on.

Count before you shrink. Following that order alone removed most of the mistakes I used to make with preprocessing.

Images are counted by tile, not by file

The first thing worth knowing is that the API does not price "an image" as one unit.

Google's image-understanding documentation says, in essence:

  • An image with both dimensions at or below 384px costs 258 tokens.
  • Larger images are split into 768×768 tiles, and each tile costs 258 tokens.
  • The tile count follows from a crop unit of roughly the shorter side divided by 1.5. The documentation's example is a 960×540 image, which comes out to 6 tiles.

That description is approximate, so I turned it into a small estimator. Clamping the crop unit to 256–768 is my own approximation for estimation purposes.

import math
 
def estimate_image_tokens(width: int, height: int) -> tuple[int, int]:
    """Estimate (tiles, tokens) from the documented tile rule.
 
    This is a rough guide. Confirm with count_tokens (below).
    """
    if max(width, height) <= 384:
        return 1, 258
    unit = math.floor(min(width, height) / 1.5)
    unit = min(max(unit, 256), 768)  # my approximation for estimating
    tiles = math.ceil(width / unit) * math.ceil(height / unit)
    return tiles, tiles * 258

Here is what it gives for common sizes, assuming 4:3 photos.

SizeEstimated tilesEstimated tokens
4032×3024 (iPhone default)246,192
2048×153661,548
1280×96041,032
1024×76841,032
768×57641,032
384×2881258

What surprised me when I built this table is that 1280px, 1024px, and 768px all land on the same number. If the estimate holds, trimming from 1024px down to 768px saves no tokens at all. Tokens only drop when you cross one of the step boundaries.

If you assume smaller is always cheaper, you can shrink too far, lose accuracy, and pay exactly the same.

Why resizing on the client matters

The API adjusts oversized images internally, but that is there to let the request through, not to lower your bill. Resizing first wins on three fronts.

  1. Token usage falls with tile count. Going from 4032×3024 to a 1024px edge takes the estimate from 24 tiles to 4.
  2. Uploads get faster. A multi-megabyte JPEG becomes roughly 200KB, which is a visible difference on a home connection.
  3. You stay further from the request limit. With inline data, the prompt plus the bytes must fit within 20MB for the whole request, so smaller images leave room for more of them.

The helper function I reuse

Pillow's thumbnail() keeps the aspect ratio while constraining the longest edge, so you don't compute new dimensions yourself.

from PIL import Image, ImageOps
from io import BytesIO
 
def prepare_image_for_gemini(
    src_path: str,
    max_side: int = 1024,
    jpeg_quality: int = 85,
) -> tuple[bytes, str]:
    """Resize and re-encode an image for the Gemini API.
 
    - Longest edge becomes max_side (aspect ratio preserved)
    - Re-encoded as JPEG (transparency is dropped)
    - Returns (bytes, mime_type)
    """
    with Image.open(src_path) as img:
        # Bake the EXIF orientation into the actual pixels
        img = ImageOps.exif_transpose(img)
        # JPEG cannot store alpha or palette modes
        if img.mode != "RGB":
            img = img.convert("RGB")
        img.thumbnail((max_side, max_side), Image.Resampling.LANCZOS)
        buf = BytesIO()
        img.save(buf, format="JPEG", quality=jpeg_quality, optimize=True)
        return buf.getvalue(), "image/jpeg"

And the call site:

from google import genai
from google.genai import types
 
client = genai.Client(api_key="YOUR_API_KEY")
image_bytes, mime = prepare_image_for_gemini("photo.jpg", max_side=1024)
 
resp = client.models.generate_content(
    model="gemini-2.5-flash",
    contents=[
        types.Part.from_bytes(data=image_bytes, mime_type=mime),
        "Return the product name and an estimated price as JSON.",
    ],
)
print(resp.usage_metadata)

Image.Resampling.LANCZOS is the Pillow 9.1.0+ spelling. On older Pillow, use Image.LANCZOS.

On ImageOps.exif_transpose(): the documentation doesn't discuss EXIF at all. It only advises verifying that images are correctly rotated. Baking the orientation into the pixels is a one-line way to take that question off the table. I once had a landscape shot arrive sideways and the model misread a product label, and that was enough to make me keep the line.

Count with count_tokens before trusting a table

My table is just my own arithmetic. Models change, and counting rules can change with them, so I measure with the model I actually call.

from google import genai
from google.genai import types
 
client = genai.Client(api_key="YOUR_API_KEY")
 
for size in (4032, 1280, 1024, 768, 384):
    data, mime = prepare_image_for_gemini("test.jpg", max_side=size)
    counted = client.models.count_tokens(
        model="gemini-2.5-flash",
        contents=[types.Part.from_bytes(data=data, mime_type=mime)],
    )
    print(size, len(data), counted.total_tokens)

count_tokens accepts image parts as well as text, so you can compare candidate sizes with the exact input before spending anything on generation. Run it on one of your real photos and the step pattern shows up. If it disagrees with my table, trust the measurement over the table.

When a count_tokens estimate and your actual bill drift apart, this write-up on count_tokens versus billed tokens helps with the diagnosis.

How small is too small?

Accuracy usually gives out before cost does. Across roughly 200 product images, here is what worked for my use cases, so treat it as a starting point.

  • Product labels and OCR: keep the longest edge at 1280px or above so fine print survives
  • Object recognition and category classification: 1024px is plenty
  • General scene understanding: 768px is usually fine
  • Face features, for privacy-safe use cases only: stay at 1280px or above

Overlay the table above and 1280, 1024, and 768 are all the same four tiles. In token terms, dropping to 768px buys nothing, so I pick 1024px or 1280px and keep the accuracy margin.

For OCR, I get steadier results by cropping the text region first (using pytesseract to find a rough box) and then resizing only that region.

If images are being rejected outright rather than read badly, the diagnosis guide for "cannot see the image" responses covers mime_type and orientation problems.

What about HEIC photos from an iPhone?

Depending on settings, iPhones save HEIC. The documented supported formats include image/heic and image/heif, so sending HEIC as-is is possible.

To resize, though, you need Pillow to open the file, and stock Pillow can't read HEIC. Adding pillow-heif and registering it lets the helper work unchanged.

from pillow_heif import register_heif_opener
 
register_heif_opener()  # Image.open() now understands HEIC
image_bytes, mime = prepare_image_for_gemini("IMG_0001.HEIC", max_side=1024)

Because the output is always re-encoded as JPEG, the mime_type you send is always image/jpeg. That keeps format branching out of the calling code, which is the main reason I like this shape.

File API or inline data

With inline data, the whole request (prompt, system instructions, and image bytes together) has to fit in 20MB. Beyond that, use the File API. After shrinking to 1024px, single-image recognition rarely comes close to the limit.

I reach for the File API in just two cases:

  • I reuse the same image across several requests (uploaded files are kept for 48 hours)
  • The asset is a video or a large PDF that can't go inline

For one-off recognition, inline saves a round trip and feels faster. A single request can carry up to 3,600 images, so for large batches it's worth checking which you hit first, that count or the 20MB ceiling.

Gemini 3 adds media_resolution

On Gemini 3 generation models, a media_resolution parameter sets the maximum number of tokens allocated to each input image or video frame. According to the documentation, higher settings improve detail recognition at the cost of more tokens and more latency.

The line I draw:

  • I decide the physical size of the image with Pillow.
  • I tell the API how many tokens each image may use with media_resolution.

They do different jobs, so I keep both in mind instead of relying on only one. For per-level token numbers, check the current table in the documentation.

Checking the effect in your own project

Batch jobs show the difference clearly. A script that processed a few hundred product images took about three hours before preprocessing and around 40 minutes after I inserted prepare_image_for_gemini. I think upload time and token count both contributed.

When you measure, I'd go in this order:

  1. Pick 5–10 representative images.
  2. Run count_tokens on the original and on the 1024px version.
  3. For accuracy-sensitive work, compare the outputs for the same prompt.

Only with the numbers and the outputs side by side can you draw the line for how small is safe.

What to try next

If a project of yours still sends raw camera photos, put prepare_image_for_gemini in front of the call and run count_tokens on one representative image before and after. That single comparison tells you most of what you need to know, and your next invoice will confirm the rest.

Share

Thank You for Reading

Gemini Lab is ad-free, supported entirely by members like you. We publish practical guides daily with implementation code, benchmarks, and production-ready patterns. If you've found it useful, we'd love to have you on board.

  • ✦Copy-paste ready implementation code
  • ✦New advanced guides published daily
  • ✦$5/mo or $10 for lifetime access
View Membership →

If you found this article helpful, a small tip ($1.50) would mean a lot to us. Your support helps keep this site ad-free and covers server and hosting costs.

Related Articles

◈ API / SDK2026-05-18
Building Automatic Wallpaper Category Classification with Gemini Vision
An indie developer shares how they implemented automatic wallpaper image classification with the Gemini Vision API — including accuracy results, real pitfalls, structured-output tips, and a cost comparison with GPT-4o Vision.
◈ API / SDK2026-05-16
Testing Gemini Vision for Wallpaper Auto-Classification — Real Accuracy Numbers and Pitfalls
A hands-on record of automating wallpaper image classification with Gemini Vision — moving from 67% to 87% accuracy, and using a confidence threshold to cut human review down to 15% of the batch.
◈ API / SDK2026-05-14
Controlling thinking_budget in Gemini 2.5 Pro — Cut Costs by 70% Without Sacrificing Reasoning Quality
Leaving thinking_budget unset in Gemini 2.5 Pro leads to unexpected costs. This guide covers task-level budget design, dynamic control, and production monitoring with working Python code.