Image Analysis from URLs and Uploaded Files

Ma Mahalakshmi V Updated 16 Sep 2026
6 min read ·Lesson 98 of 224

Two Ways to Get an Image to the Model

Lesson 2 covered the URL form of input_image, where you pass a public link and the model's provider fetches the bytes itself. That approach only works when the image already lives somewhere reachable over the public internet. Most real applications don't have that luxury — the image is a file the user just uploaded from their phone, a screenshot captured locally, or a document sitting in a private database. For those cases, the SDK supports sending the image data directly, encoded as base64 text embedded in the request itself.

This lesson covers both paths in more depth than Unit 7 did, and gives you a clear rule for choosing between them.

Sending a Local File as Base64

To send a file you have on disk, read its bytes, encode them as base64, and build a data: URI string for the image_url field:

import base64
from openai import OpenAI

client = OpenAI()


def encode_image(path: str) -> str:
    with open(path, "rb") as image_file:
        encoded_bytes = base64.b64encode(image_file.read())
    return encoded_bytes.decode("utf-8")


image_base64 = encode_image("receipts/march_grocery.jpg")

response = client.responses.create(
    model="gpt-5.6-terra",
    input=[
        {
            "role": "user",
            "content": [
                {"type": "input_text", "text": "What is the total amount on this receipt?"},
                {
                    "type": "input_image",
                    "image_url": f"data:image/jpeg;base64,{image_base64}",
                },
            ],
        }
    ],
)

print(response.output_text)

Walking through this example:

  • encode_image opens the file in binary mode ("rb") because image bytes are not text, and text-mode reading would corrupt them by attempting character decoding.
  • base64.b64encode converts the raw bytes into an ASCII-safe representation. Base64 exists because JSON — the format the SDK ultimately sends over HTTP — is a text-based format that cannot safely carry arbitrary binary bytes; base64 re-encodes those bytes as plain text characters that survive JSON encoding intact.
  • The resulting string is prefixed with data:image/jpeg;base64,, forming what is called a "data URI." This prefix tells the receiving system two things: the MIME type of the content (image/jpeg) and the encoding used (base64). Without the correct MIME type prefix, the model's provider would not know how to decode the following bytes back into an image.
  • The final image_url value looks like a URL syntactically, but no network request is made to fetch it — the image data is already embedded directly in the request payload.

Why Not Always Just Use a URL?

You could, in principle, upload every image to a public cloud bucket first and then send a URL. Many teams do this. But it adds infrastructure (a storage bucket, public access rules, a cleanup policy for temporary files) and a privacy consideration (temporarily public files, even under obscure paths, are not truly private). Sending base64 data directly avoids all of that: the image never needs to exist anywhere except in memory during the request. The trade-off is payload size — base64 encoding inflates the data by roughly 33%, and very large images increase request size and latency accordingly.

Choosing Between URL and Base64

ConsiderationURL-based image_urlBase64 data URI
Image already public onlineSimple, no extra encodingUnnecessary extra step
Image is local, private, or user-uploadedNot usable directlyCorrect choice
Very large imagesNo payload size penalty on your sideIncreases request size ~33%
Need to avoid storing the image anywhereRequires temporary hostingNo hosting needed
Debuggability (can you open the link yourself?)Easy to inspect in a browserHarder to inspect without decoding

A practical rule: if the image is already sitting at a stable, public URL, use that URL directly and skip encoding entirely — it is simpler and avoids inflating your request size. If the image originates from your user, your filesystem, or any private source, encode it as base64 and send it inline.

Handling User-Uploaded Files in a Web Application

A common real-world pattern is a web backend that receives an uploaded file (for example, through a form submission) and needs to forward it to the model without ever writing it to disk. You can encode the in-memory bytes directly:

import base64
from openai import OpenAI

client = OpenAI()


def analyze_uploaded_image(file_bytes: bytes, mime_type: str, question: str) -> str:
    encoded = base64.b64encode(file_bytes).decode("utf-8")
    data_uri = f"data:{mime_type};base64,{encoded}"

    response = client.responses.create(
        model="gpt-5.6-terra",
        input=[
            {
                "role": "user",
                "content": [
                    {"type": "input_text", "text": question},
                    {"type": "input_image", "image_url": data_uri},
                ],
            }
        ],
    )
    return response.output_text

This function takes the raw bytes your web framework hands you (for example, from an uploaded form field), along with the MIME type reported by the upload (such as "image/png" or "image/jpeg"), and the user's question. It never touches the filesystem, which is both faster and avoids leaving temporary files that need cleanup. Notice that the MIME type is a parameter here rather than hardcoded — different uploads can be PNG, JPEG, WEBP, or other formats, and the data URI must accurately declare which one it is, since an incorrect MIME type can cause the image to fail decoding on the receiving end even though the bytes themselves are fine.

Common Mistakes

Encoding the file in text mode instead of binary mode, i.e., opening with open(path, "r") instead of open(path, "rb"). Text mode applies character decoding to the bytes, which corrupts binary image data before it ever reaches base64.b64encode, typically causing an exception or a corrupted, unreadable image on the model's side.

Forgetting to decode the base64 bytes object back to a string, and passing the raw bytes object returned by base64.b64encode directly into an f-string or JSON payload. This produces a string with a b'...' wrapper visible in it. Always call .decode("utf-8") on the result before using it in the data URI.

Mismatching the declared MIME type and the actual file format — for example, hardcoding image/jpeg in the data URI prefix for a file that is actually a PNG. This is easy to do when the MIME type is copy-pasted from an earlier example rather than derived from the actual upload. Always use the MIME type that matches the real file format, ideally read from the upload metadata rather than assumed.

Best Practices

Prefer URLs for anything already hosted and stable, and reserve base64 encoding for genuinely private, local, or ephemeral images, since it keeps request payloads smaller and requests easier to debug.

Validate file size before encoding, so you can reject or downscale oversized images with a clear error message rather than sending an enormous base64 payload and receiving a cryptic failure from the API (image size and format limitations are covered in depth in Lesson 8).

Centralize your encoding logic in one helper function, like encode_image above, rather than duplicating base64-encoding code across every place in your application that sends an image — this makes it much easier to add validation, logging, or format checks in one place later.

0 Comments

Reviewed before they appear

No comments yet.

OpenAI SDK
Introduction to the OpenAI SDK Setting Up Python Creating an API Key Your First Call — client.responses.create() and response.output_text Understanding Billing, Credits, and What a Request Costs Why Responses Replaced Chat Completions Anatomy of a Request: model, input, and instructions Anatomy of a Response: The Typed output Array, Not Just Text Roles: User, Assistant, and Developer/System Choosing a Model, and Reading the Models Page Instead of Memorizing Names Instructions vs. Input Writing Prompts That Get Consistent Results Few-Shot Examples Reasoning Models and the reasoning Parameter Debugging a Prompt That Misbehaves Why Streaming Matters for User Experience stream=True and Iterating Over Events Handling the Event Types You Actually Care About Background Mode for Long-Running Jobs Project — Add Live Streaming to Your Chatbot The Problem With Parsing Free Text JSON Schema and Strict Mode Pydantic Models With the SDK's Parse Helpers Handling Refusals and Validation Failures Project — A Resume-to-JSON Extractor Working With input_image input_file, PDFs, and the Files API Image Generation Speech-to-Text and Text-to-Speech Project: A PDF Question-Answering Script What Function Calling Is Defining a Tool Schema The Full Loop Multiple Tools Errors, Timeouts, and Untrusted Arguments Project: A Weather Assistant Web Search File Search and Vector Stores Code Interpreter Remote MCP Servers and Connectors Project: A Research Assistant What an Embedding Is, Without the Maths Generating and Storing Embeddings Similarity Search From Scratch Hosted Vector Stores vs. Rolling Your Own A Small RAG App Over a Folder of Notes Agents vs. a Single API Call — When You Need One pip install openai Giving Agents Tools Handoffs and Multi-Agent Triage Guardrails and Approvals Tracing and Observing What Your Agent Did A Multi-Agent Support Desk Error Codes and What Each One Means Retries, Timeouts, and Backoff Rate Limits and Spend Limits Prompt Caching and Cost Optimisation The Batch API for Bulk Work Async Clients and Concurrency Moderation and Safety Best Practices Designing the App Backend With FastAPI Streaming to a Simple Frontend Deploying and a Cost/Safety Checklist Why Web Search Is Useful for Current Information Using the Web Search Tool with the Responses API Configuring Search Behavior for Application Use Cases Understanding Citations and Source Attribution Where to Go Next Building a Research Assistant with Web Search Combining Web Search with Structured Outputs Handling Conflicting or Low-Quality Web Sources Reducing Unsupported Claims with Grounded Generation Testing Freshness-Sensitive AI Answers Production Considerations for Web-Grounded Applications Understanding File Search and Retrieval-Augmented Generation Creating and Organizing Vector Stores Uploading Documents for Retrieval Connecting Vector Stores to Responses API Requests Designing Document Metadata and Filtering Strategies Building a PDF Question-Answering Application Improving Retrieval Quality With Better Document Preparation Handling Missing Evidence and Retrieval Failures Combining File Search With Web Search Building a Production Knowledge-Base Assistant What the Code Interpreter Tool Is Designed For Running Python-Based Analysis Through the OpenAI SDK Uploading Datasets for Analysis Analyzing CSV and Spreadsheet Data Generating Charts and Data Summaries Handling Generated Files and Downloadable Artifacts Building a Data-Analysis Assistant Combining Code Execution with Structured Outputs Validating Generated Calculations and Results Security and Sandbox Considerations for Code Execution Understanding Multimodal Input with the OpenAI SDK Sending Images to a Model Image Analysis from URLs and Uploaded Files Extracting Text and Information from Screenshots Building an Image-Question-Answering Application Combining Image Input with Structured Output Analyzing Multiple Images in One Request Handling Image Quality and Input Limitations Designing Multimodal Prompts for Reliable Results Building a Practical Vision-Powered Python Application Understanding Speech-to-Text and Text-to-Speech Workflows Transcribing Audio with the OpenAI SDK Working with Uploaded Audio Files Handling Timestamps and Transcription Metadata Building a Meeting Transcription Workflow Generating Spoken Responses from Text Handling Long Audio and Processing Failures Combining Audio with Text and Tool Calling Building an End-to-End Python Voice Application What Embeddings Are and When to Use Them Generating Embeddings With the OpenAI API Preparing Text for Embedding Comparing Vectors With Cosine Similarity Building a Simple Semantic Search Engine in Python Storing Embeddings in a Database Metadata Filtering for Semantic Search Chunking Strategies for Better Retrieval Evaluating Semantic Search Quality Building a Document Similarity Application When Batch Processing Makes Sense Designing Large-Volume AI Processing Pipelines Using Asynchronous Python with the OpenAI SDK Running Concurrent Requests Safely Controlling Concurrency and Avoiding Rate Limits Tracking Batch Job Progress Handling Partial Failures in Bulk Workloads Retrying Failed Items Without Duplicating Successful Work Designing Resumable AI Processing Jobs Building a Production Batch-Processing Pipeline Batch Processing Makes Sense Large-Scale AI Processing Pipelines Async Python with OpenAI SDK Safe Concurrent Requests Concurrency & Rate Limits Batch Progress Tracking Partial Failure Handling Safe Retry Handling Resumable AI Jobs Production Batch Pipeline System–User Data Separation Reusable App Instructions Prompt Templates & Variables Extraction & Classification Prompts Summarization & Transformation Prompts Explicit Output Requirements Prompt Version Management Prompt Testing & Evaluation Reusable Python Prompt Library API Key Security Secure API Key Storage Secure Secret Management Prompt Injection Prevention Trusted vs. Untrusted Content Tool Argument Validation Sensitive Data Handling Secure Logging AI Action Authorization Production AI Security Checklist Why AI Applications Need Evaluation Beyond Unit Tests Unit Testing OpenAI SDK Integration Code Mocking API Responses in Python Tests Testing Structured Outputs Against Schemas Testing Tool-Calling Workflows Building a Small Evaluation Dataset Measuring Accuracy, Consistency, and Failure Rates Regression Testing Prompts and Model Changes Human Evaluation Versus Automated Evaluation Creating a Repeatable Evaluation Pipeline AI Request Monitoring Token Cost Management Usage Metrics Design Reducing Model Calls Prompt & Context Optimization Model Selection & Optimization AI Caching Strategies Interactive Latency Optimization Usage Dashboards & Budget Alerts Performance & Cost Checklist Every API Call Starts Fresh Fixing API Statelessness Server-Side Conversation Memory Limits of Response Chaining What We're Building Conversation Memory Challenges Preparing an OpenAI SDK Application for Deployment Environment-Specific Configuration for Development and Production Deploying a Python AI Service with Docker Container Health Checks and Startup Configuration Managing Secrets in Cloud Deployments Background Workers for Long-Running AI Tasks Queues and Asynchronous Job Architectures Scaling AI Workloads Horizontally Monitoring Production Incidents and Failures Production Deployment Checklist for OpenAI SDK Applications Reusable OpenAI Service Classes AI Client Dependency Injection Typed AI Responses Python Configuration Management AI Request Decorators Centralized AI Error Handling Clean SDK Abstractions Reusable OpenAI Utilities Internal AI Python Libraries SDK Integration Maintenance Production AI Chatbot Document Q&A System Web Research Assistant Customer Support Agent AI Data Analysis Assistant Image Analysis App Meeting Transcription & Summary Semantic Document Search Multi-Tool AI Agent Production OpenAI SDK App Why "It Looked Fine When I Tested It" Isn't Enough Timing Note Status Note Pre-Decision Status Note Current Availability Note
Ask about this post
AI Ask about this post

Ask questions about Image Analysis from URLs and Uploaded Files and get answers drawn from it.

Signed-in readers only.