Skip to content
Fondazione ITS INCOM

Examples · Programming

Pictures in Python

Generate a picture and save the PNG, ask for two variants at once with the n parameter, and use a seed to get the same picture again.

Intermediate · 30 min

What you need

A key and the openai library, as in Your first API call in Python.

The model

Z-Image Turbo (z-image-turbo), the school's picture model. It makes PNG pictures in three sizes: 1024x1024 (square, the default), 1024x1536 (portrait) and 1536x1024 (landscape). A picture takes about ten seconds, a little more in portrait or landscape.

The program

Save it as picture.py:

import base64
import os

from openai import OpenAI

client = OpenAI(
    base_url="https://api.ai.itsincom.org/v1",
    api_key=os.environ["API_KEY"],
)

result = client.images.generate(
    model="z-image-turbo",
    prompt="A small robot watering plants in a greenhouse, flat vector illustration, soft daylight",
    size="1024x1024",
)

with open("robot.png", "wb") as f:
    f.write(base64.b64decode(result.data[0].b64_json))
print("robot.png is ready")

The picture comes back inside the answer, as text in base64: b64decode turns it back into the bytes of a PNG.

Two variants with n

Save it as variants.py:

import base64
import os

from openai import OpenAI

client = OpenAI(
    base_url="https://api.ai.itsincom.org/v1",
    api_key=os.environ["API_KEY"],
)

result = client.images.generate(
    model="z-image-turbo",
    prompt="A small robot watering plants in a greenhouse, flat vector illustration, soft daylight",
    n=2,
)

for i, picture in enumerate(result.data, 1):
    with open(f"robot-{i}.png", "wb") as f:
        f.write(base64.b64decode(picture.b64_json))
print(len(result.data), "pictures")

n goes from 1 to 4. The pictures are made one after the other, so two take twice as long.

The same picture again, with seed

Every request draws a new picture, even with the same prompt. A seed fixes the starting point: the same prompt with the same seed gives the same picture again. The library has no seed argument, so it goes in extra_body. Save it as same_again.py:

import base64
import os

from openai import OpenAI

client = OpenAI(
    base_url="https://api.ai.itsincom.org/v1",
    api_key=os.environ["API_KEY"],
)

pictures = []
for attempt in (1, 2):
    result = client.images.generate(
        model="z-image-turbo",
        prompt="A small robot watering plants in a greenhouse, flat vector illustration, soft daylight",
        extra_body={"seed": 1234},
    )
    pictures.append(base64.b64decode(result.data[0].b64_json))
    with open(f"seed-{attempt}.png", "wb") as f:
        f.write(pictures[-1])

print("the same picture" if pictures[0] == pictures[1] else "two different pictures")

What you should see

Good to know

Exercise

All examples