0
0

OpenAI Dalle-3 APIを使った画像生成Pythonサンプル

Posted at

背景

  • Dalle-3をPython APIで呼び出す
  • 出力方式がurlとb64_jsonがあるので両方やり方メモ

response_format = url

  • httpで画像にアクセスできるurlがかえります
  • ただし、1時間しか有効ではないので注意
from openai import OpenAI

client = OpenAI()
res = client.images.generate(
    model="dall-e-3",
    prompt="a cat in the park",
    size="1024x1024",
    quality="hd",
    response_format="url",
    style="vivid"
)
return res.data[0].url

response_format = b64_json

  • 指定したpathにpng形式で保存します
  • base64.b64decode でbytesのデータが取得できるのでそれを書き込みます
from openai import OpenAI

client = OpenAI()
res = client.images.generate(
    model="dall-e-3",
    prompt="a cat in the park",
    size="1024x1024",
    quality="hd",
    response_format="b64_json",
    style="vivid"
)
image_bytes = base64.b64decode(res.data[0].b64_json)
with open(filepath, 'wb') as file:
    file.write(image_bytes)
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0