imageService.ts 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. import type { Recipe } from '@/types'
  2. // 图片生成模型配置 - 从环境变量读取
  3. const IMAGE_CONFIG = {
  4. apiKey: import.meta.env.VITE_IMAGE_GENERATION_API_KEY,
  5. baseURL: import.meta.env.VITE_IMAGE_GENERATION_BASE_URL || 'https://open.bigmodel.cn/api/paas/v4/',
  6. model: import.meta.env.VITE_IMAGE_GENERATION_MODEL || 'cogview-3-flash'
  7. }
  8. const API_URL = `${IMAGE_CONFIG.baseURL}images/generations`
  9. export interface GeneratedImage {
  10. url: string
  11. id: string
  12. }
  13. export const generateRecipeImage = async (recipe: Recipe): Promise<GeneratedImage> => {
  14. // 构建图片生成的提示词
  15. const prompt = buildImagePrompt(recipe)
  16. const sizeToUse = { width: 1024, height: 1024 }
  17. try {
  18. const response = await fetch(API_URL, {
  19. method: 'POST',
  20. headers: {
  21. 'Content-Type': 'application/json',
  22. Authorization: `Bearer ${IMAGE_CONFIG.apiKey}`
  23. },
  24. body: JSON.stringify({
  25. model: IMAGE_CONFIG.model,
  26. prompt: prompt,
  27. size: `${sizeToUse.width}x${sizeToUse.height}`,
  28. n: 1,
  29. style: 'vivid',
  30. quality: 'hd'
  31. })
  32. })
  33. if (!response.ok) {
  34. throw new Error(`API请求失败: ${response.status}`)
  35. }
  36. const data = await response.json()
  37. if (data.data && data.data.length > 0) {
  38. return {
  39. url: data.data[0].url,
  40. id: `${recipe.id}-${Date.now()}`
  41. }
  42. } else {
  43. throw new Error('API返回数据格式错误')
  44. }
  45. } catch (error) {
  46. console.error('生成图片失败:', error)
  47. throw error
  48. }
  49. }
  50. const buildImagePrompt = (recipe: Recipe): string => {
  51. // 根据菜谱信息构建详细的图片生成提示词
  52. const ingredients = recipe.ingredients.join('、')
  53. const cuisineStyle = recipe.cuisine.replace('大师', '').replace('菜', '')
  54. return `一道精美的${cuisineStyle}菜肴:${recipe.name},主要食材包括${ingredients}。菜品摆盘精致,色彩丰富,光线柔和,专业美食摄影风格,高清画质,餐厅级别的视觉效果。背景简洁,突出菜品本身的美感。`
  55. }