python
import base64
import matplotlib.pyplot as plt
from openai import OpenAI
from PIL import Image
from io import BytesIO
api_key = "sk-xxxxx"
def base64_to_image(base64_string):
try:
image_data = base64.b64decode(base64_string)
image_buffer = BytesIO(image_data)
image = Image.open(image_buffer)
return image
except Exception as e:
print(f"An error occurred: {e}")
return None
client = OpenAI(api_key=api_key)
response = client.images.generate(
model="dall-e-3",
prompt="A spaceship flying through the universe", # an example
size="1024x1024",
quality="standard",
n=1,
response_format='b64_json'
)
image_b64 = response.data[0].b64_json
generated_image = base64_to_image(image_b64)
if generated_image:
plt.imshow(generated_image)
plt.axis("off")
plt.show()
输出: