banana_pro.py 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. from google import genai
  2. from google.genai import types
  3. from PIL import Image
  4. import os
  5. from dotenv import load_dotenv
  6. from typing import List, Optional
  7. load_dotenv()
  8. client = genai.Client(api_key=os.getenv("BANANA_PRO_KEY"))
  9. print(f"BANANA_PRO_KEY: {os.getenv('BANANA_PRO_KEY')}")
  10. def generate_image_from_prompt_and_images(
  11. prompt: str,
  12. image_paths: List[str],
  13. aspect_ratio: str = "16:9",
  14. resolution: str = "2K"
  15. ) -> Optional[Image.Image]:
  16. """
  17. 使用 Gemini API 生成图像
  18. 参数:
  19. prompt: 文本提示词
  20. image_paths: 参考图像路径列表
  21. aspect_ratio: 图像宽高比,可选值: "1:1","2:3","3:2","3:4","4:3","4:5","5:4","9:16","16:9","21:9"
  22. resolution: 图像分辨率,可选值: "1K", "2K", "4K"
  23. 返回:
  24. 生成的图像对象 (PIL Image),如果生成失败则返回 None
  25. """
  26. # 构建内容列表:包含提示词和所有参考图像
  27. contents = [prompt]
  28. for image_path in image_paths:
  29. contents.append(Image.open(image_path))
  30. # 调用 API 生成内容
  31. response = client.models.generate_content(
  32. model="gemini-3-pro-image-preview",
  33. contents=contents,
  34. config=types.GenerateContentConfig(
  35. response_modalities=['TEXT', 'IMAGE'],
  36. image_config=types.ImageConfig(
  37. aspect_ratio=aspect_ratio,
  38. image_size=resolution
  39. ),
  40. )
  41. )
  42. # 处理响应,提取图像
  43. for part in response.parts:
  44. if part.text is not None:
  45. print(part.text)
  46. elif image := part.as_image():
  47. return image
  48. return None
  49. if __name__ == "__main__":
  50. # 测试代码
  51. prompt = "男人在月球上行走"
  52. image_paths = ["./test_output/output/front_portrait_0.png"]
  53. aspect_ratio = "16:9"
  54. resolution = "1K"
  55. generated_image = generate_image_from_prompt_and_images(
  56. prompt=prompt,
  57. image_paths=image_paths,
  58. aspect_ratio=aspect_ratio,
  59. resolution=resolution
  60. )
  61. if generated_image:
  62. generated_image.save("xxxxxxx.png")
  63. print("图像已保存到 xxxxxxx.png")