Skip to content

Instantly share code, notes, and snippets.

@kujirahand
Created November 26, 2025 10:47
Show Gist options
  • Select an option

  • Save kujirahand/9253907b5caf083f69fe10409c9e55fd to your computer and use it in GitHub Desktop.

Select an option

Save kujirahand/9253907b5caf083f69fe10409c9e55fd to your computer and use it in GitHub Desktop.
マイナビPython連載のサンプルコード「image-gen.py」
import base64
from openai import OpenAI
import typer
# 画像生成用のプロンプトテンプレート --- (*1)
PROMPT_TEMPLATE = """\
指示: {prompt}
画風: {style}
"""
# Typerアプリケーションの作成 --- (*2)
app = typer.Typer()
@app.command() # 関数の引数を指定 --- (*3)
def generate(
prompt: str = typer.Argument(..., help="画像生成のためのプロンプト"),
style: str = typer.Option("浮世絵風", "--style", "-S", help="画風の指定"),
output: str = typer.Option("image.png", "--output", "-o", help="出力ファイル"),
size: str = typer.Option("1024x1024", "--size", "-s", help="画像サイズ"),
model: str = typer.Option("gpt-image-1-mini", "--model", "-m", help="使用モデル"),
input: str = typer.Option(None, "--input", "-i", help="入力画像ファイル"),
):
"""OpenAI APIを使って画像を生成・編集するプログラム""" # --- (*4)
client = OpenAI() # OpenAIクライアントの初期化 - 環境変数から自動取得
typer.echo(f"画像を生成中: {prompt}")
typer.echo(f"サイズ: {size}, モデル: {model}")
try:
if input is None:
# 画像生成 --- (*5)
response = client.images.generate(
model=model,
prompt=PROMPT_TEMPLATE.format(
prompt=prompt, style=style),
size=size,
)
else:
# 画像変換 --- (*6)
response = client.images.edit(
model=model,
image=open(input, "rb"),
prompt=prompt,
size=size,
)
# 生成された画像のURLを取得して保存 --- (*7)
image_base64 = response.data[0].b64_json
image_bytes = base64.b64decode(image_base64)
with open(output, "wb") as f:
f.write(image_bytes)
typer.echo(f"画像を保存しました: {output}")
except Exception as e:
typer.echo(f"エラー: {e}", err=True)
raise typer.Exit(code=1)
if __name__ == "__main__":
app()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment