skip to content
Alvin Lucillo

Using Foundry AI model to generate image

/ 1 min read

To generate an image, deploy a model that is capable of text to image like FLUX.2-pro that is used below.

import base64
import os
import requests

endpoint = "https://redacted-resource.services.ai.azure.com/providers/blackforestlabs/v1/flux-2-pro"
deployment_name = "FLUX.2-pro"
api_key = "redacted-key"

payload = {
    "model": "FLUX.2-pro",
    "prompt": "A cute baby polar bear",
    "width": 1024,
    "height": 1024,
    "output_format": "png",
    "num_images": 1,
}

response = requests.post(
    endpoint,
    headers={
        "Content-Type": "application/json",
        "Authorization": f"Bearer {api_key}",
    },
    json=payload,
    timeout=180,
)

response.raise_for_status()
result = response.json()

images = result.get("data")
if not isinstance(images, list) or not images:
    raise ValueError(f"Response does not contain an image list; keys: {list(result)}")

first_image = images[0]
if not isinstance(first_image, dict):
    raise ValueError("The first image response has an unexpected format")

output_path = "output.png"
encoded_image = first_image.get("b64_json")
image_url = first_image.get("url")

if encoded_image:
    # Also accept a complete data URL, not only raw Base64 text.
    if encoded_image.startswith("data:"):
        encoded_image = encoded_image.split(",", 1)[1]
    image_bytes = base64.b64decode(encoded_image)
elif image_url:
    image_response = requests.get(image_url, timeout=180)
    image_response.raise_for_status()
    image_bytes = image_response.content
else:
    raise ValueError("The image response contains neither 'b64_json' nor 'url'")

with open(output_path, "wb") as output_file:
    output_file.write(image_bytes)

print(f"Saved image to {output_path}")
azgenimage.py

Saved image to output.png