Skip to content
,

Claude Vision API Tutorial: Send Images and PDFs in Python (2026)

13โ€“20 minutes
Woman on a rooftop terrace holding a tablet with a CLAUDE VISION card, hook 1,296 tokens per 1MP image

Claude can read images and PDFs through the Messages API. You send a photo, screenshot, chart or a 300-page report, and Claude answers questions about it in plain text.

This tutorial shows every way to do it in Python: base64, URL and Files API file_id. It also covers the new 28-pixel token formula, PDF limits, prices and the errors you will hit.

TLDR

  • Three sources: send an image or PDF as base64, as a public url, or as a Files API file with a file_id.
  • Two block types: images go in an image block, PDFs go in a document block.
  • Token formula: an image costs ceil(width/28) x ceil(height/28) visual tokens. A 1000×1000 image is 1,296 tokens.
  • Limits: up to 600 images or PDF pages per request on 1M-context models, 8000×8000 px max, 10 MB per image, 128 MB per request.
  • Cost: images are billed as normal input tokens. 1,000 receipt photos on Claude Haiku 5.5 cost about $0.35 in total.

What Claude Vision Is and When to Use It

Every current Claude model can understand images. Anthropic’s model overview says all current models support text and image input with text output. There is no separate “vision model” to pick.

Vision is a good fit for jobs like these:

  • Data extraction: pull totals, dates and line items from receipts, invoices and forms.
  • Charts and dashboards: explain a graph, read values off an axis, or summarise a slide.
  • Screenshots: describe a UI bug, read an error dialog, or check a layout.
  • Documents: read PDFs with both text and pictures, such as reports, contracts and papers.
  • Comparisons: spot the differences between two product photos or two versions of a design.

Note: Claude only reads images. It cannot create or edit them. It also will not name real people in photos, and Anthropic warns it can be wrong on blurry, rotated or very small images under 200 pixels.

If you have never called the API before, start with our Claude API Python tutorial. This guide assumes you can already send a basic text message.

Prerequisites and Setup

Here is what you need before running the examples:

  • An API key: see how to get a Claude API key.
  • Python 3.10 or newer: the current SDK needs it.
  • The anthropic SDK: this guide was checked against anthropic 2.16.0 (released 1 December 2026). It sends API version 2026-10-21 by default.
  • Pillow (optional): used in the resize helper to keep images small and cheap.
  1. Create a virtual environment. Run python -m venv .venv and activate it.
  2. Install the packages. Run pip install -U anthropic pillow. Confirm with pip show anthropic that you have 2.x.
  3. Set your key as an environment variable. On macOS or Linux run export ANTHROPIC_API_KEY="sk-ant-...". On Windows PowerShell run $env:ANTHROPIC_API_KEY="sk-ant-...". The SDK reads it automatically.
  4. Add test files. Put a receipt.jpg, a chart.png and a report.pdf next to your script.
  5. Pick a model. The examples use claude-sonnet-5-5. Swap in claude-haiku-5-5 for cheap bulk work or claude-opus-5-5 for harder documents.

Example 1: Send a Local Image as Base64

Base64 is the simplest option for a file on your disk. You read the bytes, encode them, and put them in an image block with the right media_type.

Supported types are image/jpeg, image/png, image/gif and image/webp. For animated GIFs, only the first frame is used.

import base64
import mimetypes
import anthropic

client = anthropic.Anthropic()  # reads ANTHROPIC_API_KEY

def image_block(path):
    media_type, _ = mimetypes.guess_type(path)
    with open(path, "rb") as f:
        data = base64.standard_b64encode(f.read()).decode("utf-8")
    return {
        "type": "image",
        "source": {"type": "base64", "media_type": media_type, "data": data},
    }

message = client.messages.create(
    model="claude-sonnet-5-5",
    max_tokens=1024,
    messages=[
        {
            "role": "user",
            "content": [
                image_block("receipt.jpg"),  # image first, then the question
                {"type": "text", "text": "List the store name, date, each item and the total."},
            ],
        }
    ],
)

print(message.content[0].text)
print("Input tokens:", message.usage.input_tokens)

The usage.input_tokens value includes the image tokens. Print it on your first runs so you learn what your images really cost.

Tip: Anthropic’s docs say Claude works best when the image comes before the text question. Images after text still work, but image-then-text is the safer default.

Example 2: Send an Image by URL

If the image is already online, skip the encoding. Use a url source and Anthropic fetches the file for you. This keeps your request tiny.

import anthropic

client = anthropic.Anthropic()

message = client.messages.create(
    model="claude-sonnet-5-5",
    max_tokens=1024,
    messages=[
        {
            "role": "user",
            "content": [
                {
                    "type": "image",
                    "source": {
                        "type": "url",
                        "url": "https://platform.claude.com/docs/images/vision-example.jpg",
                    },
                },
                {"type": "text", "text": "Describe this image in three bullet points."},
            ],
        }
    ],
)

print(message.content[0].text)

The URL must be publicly reachable. Links behind a login, signed links that have expired, or pages that return HTML instead of an image will fail.

Warning: URL and file_id sources do not work everywhere. On Amazon Bedrock and Google-managed Claude on Google Cloud, only base64 images are accepted, with a 5 MB per-image limit.

Example 3: Upload Once With the Files API and Compare Images

In a chat or agent loop, every request resends the whole history. With base64, the full image bytes travel again on every turn. The Files API fixes that: upload once, then send only a short file_id.

This example uploads two images, labels them, and asks Claude to compare them. Anthropic recommends a short text label such as Image 1: before each image so you can refer to them by name.

import anthropic

client = anthropic.Anthropic()

def upload(path, media_type):
    with open(path, "rb") as f:
        return client.files.upload(file=(path, f, media_type))

old = upload("design-v1.png", "image/png")
new = upload("design-v2.png", "image/png")
print("Uploaded:", old.id, new.id)

message = client.messages.create(
    model="claude-sonnet-5-5",
    max_tokens=1024,
    messages=[
        {
            "role": "user",
            "content": [
                {"type": "text", "text": "Image 1:"},
                {"type": "image", "source": {"type": "file", "file_id": old.id}},
                {"type": "text", "text": "Image 2:"},
                {"type": "image", "source": {"type": "file", "file_id": new.id}},
                {"type": "text", "text": "List every visual difference between Image 1 and Image 2."},
            ],
        }
    ],
)

print(message.content[0].text)

# Clean up when you no longer need the files
client.files.delete(old.id)
client.files.delete(new.id)

The Files API is generally available, so no beta header is needed in SDK 2.x. Uploading, listing and deleting files is free. You only pay input tokens when a file is used in a message. Our Claude Files API tutorial covers storage limits and file management in depth.

In later turns of the same conversation, Claude can still see every earlier image. A follow-up like “Which version has the bigger button?” works without sending the images again in the new turn.

Example 4: Ask Questions About a PDF

PDFs use a document block instead of an image block. The same three sources work: base64, url and file.

Here is how it works behind the scenes, per Anthropic’s PDF docs:

  1. Each page becomes an image. The API renders every page so Claude can see charts, tables and diagrams.
  2. Text is extracted too. The text of each page is sent alongside its image.
  3. Claude reads both. It can answer about the words and the visuals on any page.

This example sends a local PDF as base64 and marks it for prompt caching, so follow-up questions on the same file are much cheaper.

import base64
import anthropic

client = anthropic.Anthropic()

with open("report.pdf", "rb") as f:
    pdf_data = base64.standard_b64encode(f.read()).decode("utf-8")

def ask(question):
    message = client.messages.create(
        model="claude-sonnet-5-5",
        max_tokens=2048,
        messages=[
            {
                "role": "user",
                "content": [
                    {
                        "type": "document",
                        "source": {
                            "type": "base64",
                            "media_type": "application/pdf",
                            "data": pdf_data,
                        },
                        "cache_control": {"type": "ephemeral"},
                    },
                    {"type": "text", "text": question},
                ],
            }
        ],
    )
    u = message.usage
    print(f"in={u.input_tokens} cache_write={u.cache_creation_input_tokens} "
          f"cache_read={u.cache_read_input_tokens} out={u.output_tokens}")
    return message.content[0].text

print(ask("Summarise this report in 5 bullet points."))
print(ask("What does the chart on page 3 show?"))

The first call writes the PDF to the cache. The second call, if made within 5 minutes, reads it from the cache. Learn more in our guide to prompt caching.

Claude Platform Docs PDF support requirements: 128 MB max request size, 600 pages per request (100 under 1M context), standard PDF with no passwords
Official Claude Platform Docs PDF support page, “Check PDF requirements” (checked 3 Dec 2026).

Using a PDF from the Files API

For a big PDF you will query many times, upload it once and point to it by ID:

with open("report.pdf", "rb") as f:
    doc = client.files.upload(file=("report.pdf", f, "application/pdf"))

message = client.messages.create(
    model="claude-sonnet-5-5",
    max_tokens=1024,
    messages=[
        {
            "role": "user",
            "content": [
                {"type": "document", "source": {"type": "file", "file_id": doc.id}},
                {"type": "text", "text": "List every deadline mentioned in this document."},
            ],
        }
    ],
)
print(message.content[0].text)

Word and Excel files do not work in a document block. Convert a .docx to PDF or plain text first. Plain .txt, .csv and .md files can be uploaded with the text/plain type and used in a document block.

The Same Request With curl

Here is a base64 image request from the command line, following Anthropic’s vision docs. It encodes receipt.jpg and sends it with API version 2026-10-21.

BASE64_IMAGE_DATA=$(base64 receipt.jpg | tr -d '\n')

curl https://api.anthropic.com/v1/messages \
  -H "x-api-key: $ANTHROPIC_API_KEY" \
  -H "anthropic-version: 2026-10-21" \
  -H "content-type: application/json" \
  -d @- <<EOF
{
  "model": "claude-sonnet-5-5",
  "max_tokens": 1024,
  "messages": [{
    "role": "user",
    "content": [
      {"type": "image",
       "source": {"type": "base64", "media_type": "image/jpeg", "data": "$BASE64_IMAGE_DATA"}},
      {"type": "text", "text": "What is the total on this receipt?"}
    ]
  }]
}
EOF

For a URL image, replace the source with {"type": "url", "url": "https://..."}. For a PDF, change "type": "image" to "type": "document" and use application/pdf.

Image Size and Token Cost Formula

Quick answer: Claude splits each image into 28×28-pixel patches. One patch is one visual token, so an image costs ceil(width / 28) x ceil(height / 28) tokens, up to the model’s cap.

If you remember the old “width x height / 750” rule from older guides, it is out of date. Anthropic’s current vision page uses the 28-pixel patch formula.

Each model also has a resolution tier. Images larger than the tier’s long-edge or token limit are scaled down (keeping the aspect ratio) before Claude sees them.

Resolution tier Models Max long edge Max visual tokens
High-resolution Claude 4.7 and later (Fable 5.x, Opus 5.5, Sonnet 5.5, Haiku 5.5 and others) 2,576 px 4,784
Standard All other models (for example Haiku 4.5) 1,568 px 1,568
Claude Platform Docs vision page: images cost ceil(width/28) x ceil(height/28) visual tokens; high-resolution tier 2,576 px and 4,784 tokens, standard tier 1,568 px and 1,568 tokens
Official Claude Platform Docs Vision page, “Resolution and token cost” excerpt (checked 3 Dec 2026).

Here is what common sizes cost, from Anthropic’s table and the formula:

Image size Standard tier tokens High-res tier tokens
200×200 px 64 64
800×600 px 638 638
1000×1000 px 1,296 1,296
1200×1600 px (phone receipt) 1,564 (downscaled to about 952×1269) 2,494
1920×1080 px (Full HD screenshot) 1,560 (downscaled to 1456×819) 2,691
3840×2160 px (4K) 1,560 (downscaled to 1456×819) 4,784 (downscaled to 2576×1449)

So a high-res model can use up to about three times more tokens for the same big image. That buys sharper detail for screenshots and dense documents. If you do not need it, shrink the image first.

A resize helper that caps the token cost

This Pillow helper estimates tokens and shrinks an image until it fits a token budget you choose. Smaller requests are also faster.

import math
from PIL import Image

def visual_tokens(w, h):
    return math.ceil(w / 28) * math.ceil(h / 28)

def shrink_to_budget(path, out_path, max_edge=1568, max_tokens=1568):
    img = Image.open(path)
    w, h = img.size
    scale = min(1.0, max_edge / max(w, h))
    while visual_tokens(int(w * scale), int(h * scale)) > max_tokens:
        scale *= 0.97
    new_size = (int(w * scale), int(h * scale))
    if new_size != img.size:
        img = img.resize(new_size, Image.LANCZOS)
    img.save(out_path)
    print(f"{w}x{h} -> {new_size[0]}x{new_size[1]}, about {visual_tokens(*new_size)} tokens")

shrink_to_budget("receipt.jpg", "receipt-small.jpg")

To get the exact number before paying for a reply, call client.messages.count_tokens(model=..., messages=...) with the same content. It returns input_tokens for the whole request.

Image and PDF Limits

These limits come from Anthropic’s vision, PDF support and API overview pages (checked 3 December 2026):

Limit Value
Images per API request 600 (100 for models with a 200k context window, such as Haiku 4.5)
Images per message on claude.ai 20
Max image dimensions 8000×8000 px
Requests with more than 20 images A stricter per-image size limit applies; keep each side at or under 3,000 px to be safe
Max size per image 10 MB base64 on the Claude API; 5 MB on Amazon Bedrock
PDF pages per request 600 (100 when the context window is under 1M tokens)
PDF format Standard PDF only, no passwords or encryption
Max request size 128 MB for Messages; 256 MB for Message Batches
Files API file size 500 MB per file

All current models (Fable 5.2, Opus 5.5, Sonnet 5.5 and Haiku 5.5) have a 1M-token context window, so they get the 600 limit. In practice, the 128 MB request size or the context window often runs out first with big files.

The “more than 20 images” rule counts every image block in the request. That includes images from earlier turns you resend and screenshots inside tool results.

Claude Vision Pricing With a Worked Example

There is no extra fee for vision. Image and PDF tokens are billed as normal input tokens at the model’s rate. Here are the current prices from Anthropic’s pricing page:

Model Input / 1M tokens Output / 1M tokens Batch input / output
Claude Fable 5.2 $8 $40 $4 / $20
Claude Opus 5.5 $4 $20 $2 / $10
Claude Sonnet 5.5 $2 $10 $1 / $5
Claude Haiku 5.5 (prompts up to 100k tokens) $0.10 $0.50 $0.05 / $0.25
Claude Haiku 5.5 (prompts over 100k tokens) $0.50 $2.50 $0.25 / $1.25

Worked example: 1,000 receipt photos

Say you extract data from 1,000 phone photos of receipts, each 1200×1600 px. On a high-res model each photo is 2,494 visual tokens. Add about 50 tokens for the prompt and allow 200 output tokens per reply.

  • Input per receipt: 2,494 + 50 = 2,544 tokens. For 1,000 receipts: 2,544,000 tokens.
  • Output per receipt: 200 tokens. For 1,000 receipts: 200,000 tokens.
Model Input cost Output cost Total (standard) Total (Batch API)
Haiku 5.5 2.544M x $0.10 = $0.25 0.2M x $0.50 = $0.10 $0.35 $0.18
Sonnet 5.5 2.544M x $2 = $5.09 0.2M x $10 = $2.00 $7.09 $3.54
Opus 5.5 2.544M x $4 = $10.18 0.2M x $20 = $4.00 $14.18 $7.09

Shrinking each photo to the 1,568-token budget with the helper above cuts the image part by about 37%. For non-urgent jobs, the Message Batches API halves everything.

Note: Opus 5.5 and Fable 5.2 have adaptive thinking always on, and thinking tokens are billed as output. Real output counts can be higher than the 200 tokens assumed here, so check usage.output_tokens on a sample first.

Worked example: a 20-page PDF

Anthropic says each PDF page typically uses 1,500 to 3,000 text tokens, plus the page image. Page images are capped at 1,568 visual tokens on every model.

Take a 20-page report at about 2,000 text tokens per page plus a full 1,568-token page image. That is 20 x 3,568 = 71,360 input tokens, a high estimate.

  • First question on Sonnet 5.5 (no cache): 71,360 x $2 / 1M = $0.14, plus 1,000 output tokens at $0.01. About $0.15.
  • Cache write (5 minute) on the first call: 71,360 x $2.50 / 1M = about $0.18.
  • Each follow-up from cache: 71,360 x $0.10 / 1M = about $0.007, plus output.

With caching, ten questions on the same PDF cost about $0.35 instead of $1.50. See our Claude API pricing guide for all the multipliers.

Tips for Better Results

  • Image first, question second: put image and document blocks before your text.
  • Label multiple images: add Image 1:, Image 2: text blocks so Claude can refer to each one.
  • Keep text legible: crop to the useful area instead of sending a huge photo that gets downscaled.
  • Avoid heavy compression: strong JPEG compression can make small text unreadable.
  • Rotate pages upright: rotated pages and photos lower accuracy.
  • Use page numbers from the PDF viewer: ask about “page 3” as your viewer shows it.
  • Split huge PDFs: dense documents can fill the context window before the 600-page limit.
  • Do not trust counts or coordinates blindly: Anthropic says counts of many small objects and positions are approximate.

Claude also does not read image metadata such as EXIF, so a photo’s date or GPS data will not reach the model. Put any facts you need in the text prompt.

Need to stop images being resized at all, for example when you click on coordinates? Add "transformations": {"oversized_image": "error"} to the image block. The API then returns a 400 error with the largest size that fits, instead of quietly shrinking it.

Troubleshooting: Common Problems and Fixes

These are the vision and PDF errors developers report most. In Python, 400 errors raise anthropic.BadRequestError and 413 errors raise anthropic.ContentTooLargeError.

Error or symptom Cause Fix
400 invalid_request_error: “Image does not match the provided media type” The media_type you sent (for example image/png) does not match the real file bytes, often a JPEG renamed to .png. Detect the type from the file bytes (for example with Pillow’s Image.open(path).format) instead of the file extension.
400 error that the image is too large The base64 data is over 10 MB (5 MB on Bedrock), or a side is over 8000 px. Resize or recompress with the helper above. Remember base64 makes files about a third bigger.
400 error mentioning “many-image requests” More than 20 images in the request, and some are larger than the stricter limit. Resize every image to 3,000 px or less per side, or send 20 or fewer images.
400 error: “image dimensions … exceed the maximum image size” You set oversized_image to error and the image is too big for the model. Resize to the size the message suggests, or remove the setting.
413 request_too_large The whole request is over 128 MB, usually many base64 images or PDFs. Upload files with the Files API and send file_id sources instead.
400 error on a URL source The URL is private, expired, blocked or does not return an image or PDF. Test the link in a private browser window, or download it and send base64.
400 error on a document block The PDF is password-protected or encrypted, or you sent a .docx or .xlsx. Remove the password, or convert the file to a standard PDF or plain text.
Context window or page limit errors on PDFs Over 600 pages, or dense pages filled the context. Split the PDF into sections and ask about each one.
Bedrock or Google Cloud rejects url or file These platforms accept base64 sources only. Switch to base64 on those platforms.
429 or 529 errors under load Rate limits or temporary overload. The SDK retries twice by default. See our 429 and 529 fix guide.

Here is a small wrapper that catches the common cases:

import anthropic

client = anthropic.Anthropic()
# image_block() is the helper from Example 1

try:
    message = client.messages.create(
        model="claude-sonnet-5-5",
        max_tokens=1024,
        messages=[{"role": "user", "content": [image_block("receipt.jpg"),
                   {"type": "text", "text": "What is the total?"}]}],
    )
    print(message.content[0].text)
except anthropic.ContentTooLargeError:
    print("Request over 128 MB: use the Files API or smaller images.")
except anthropic.BadRequestError as e:
    print("Bad request (check media type, size, PDF format):", e.message)
except anthropic.APIStatusError as e:
    print("API error", e.status_code, e.message)

Frequently Asked Questions

Which Claude models support vision?

All current Claude models accept image and PDF input, including Fable 5.2, Opus 5.5, Sonnet 5.5 and Haiku 5.5. There is no separate vision model or extra switch to turn on.

How many tokens does an image use in Claude?

An image costs ceil(width/28) x ceil(height/28) visual tokens. High-res models cap this at 4,784 tokens per image and standard models at 1,568, so a 1000×1000 image uses 1,296 tokens.

Should I use base64, URL or file_id?

Use base64 for one-off local files, URL for images already online, and file_id for files you reuse or for long conversations. On Bedrock and Google-managed Google Cloud, only base64 works.

How many pages can a PDF have?

Up to 600 pages per request on 1M-context models, or 100 when the context window is under 1M tokens. The whole request must also stay under 128 MB.

Does Claude charge extra for images or PDFs?

No. Images and PDF pages are billed as normal input tokens at the model’s price. Prompt caching and the 50% Batch API discount apply to them too.

Can Claude read handwriting and charts?

Yes, Claude can read clear handwriting, charts, tables and screenshots. Accuracy drops on blurry, rotated or tiny images, so send sharp images and check important values.

Can I delete images I sent to the API?

Images sent inline cannot be deleted. Files uploaded through the Files API can be deleted with client.files.delete(file_id). Anthropic says it does not use uploaded images to train models.

Sources

Free weekly email

Get new AI guides every week

One short weekly email with our newest local AI, ComfyUI and AI tool guides. No spam, no pop-ups, just the good stuff.

Free. Unsubscribe anytime in one click. We only use your email to send this newsletter. See our privacy policy.

Woman on a rooftop terrace holding a tablet with a CLAUDE VISION card, hook 1,296 tokens per 1MP image