Using Local Base64-Encoded Images
In this lesson, you'll learn how to send a local image to the GPT-4.1 API by encoding it to Base64 and passing it as a data URI.
Prerequisites
Install the OpenAI SDK:
pip install openai
Make sure you have a local image (e.g., path_to_your_image.jpg).
The Code
import base64
from openai import OpenAI
client = OpenAI()
# Function to encode the image
def encode_image(image_path):
with open(image_path, "rb") as image_file:
return base64.b64encode(image_file.read()).decode("utf-8")
# Path to your image
image_path = "path_to_your_image.jpg"
# Getting the Base64 string
base64_image = encode_image(image_path)
response = client.responses.create(
model="gpt-4.1",
input=[
{
"role": "user",
"content": [
{ "type": "input_text", "text": "what's in this image?" },
{
"type": "input_image",
"image_url": f"data:image/jpeg;base64,{base64_image}",
},
],
}
],
)
print(response.output_text)
Explanation
base64.b64encode(...): Converts the binary image into a text format.data:image/jpeg;base64,...: Embeds the image directly without uploading it online.input_imagecan now reference any local image securely.
Use Case
Best for:
- Secure local image analysis
- Offline workflows with temporary media
- Avoiding public hosting or uploads