imageService.ts 2.0 KB

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