img2img.js 1.4 KB

123456789101112131415161718192021222324252627282930
  1. const fs = require('fs')
  2. const path = require('path')
  3. const { runWithModel, resolveSavePath } = require('./shared')
  4. /** 入参:prompt, model, imageUrl(参考图地址), savePath(可选,生成图保存路径) */
  5. async function executeImg2img ({ prompt, model, imageUrl, savePath, folderPath }) {
  6. const p = prompt != null ? String(prompt).trim() : ''
  7. const url = imageUrl != null ? String(imageUrl).trim() : ''
  8. if (!url) return { success: false, error: 'img2img 缺少 imageUrl' }
  9. const outPath = savePath ? resolveSavePath(savePath, folderPath) : null
  10. try {
  11. const result = await runWithModel('img2img', 'doubao_img2img', [p, url], model)
  12. if (!result.success) return { success: false, error: result.error || 'img2img 失败' }
  13. const data = result.data
  14. const item = data?.data?.[0]
  15. if (!item) return { success: false, error: 'img2img 无返回数据' }
  16. if (item.b64_json && outPath) {
  17. const dir = path.dirname(outPath)
  18. if (!fs.existsSync(dir)) fs.mkdirSync(dir, { recursive: true })
  19. fs.writeFileSync(outPath, Buffer.from(item.b64_json, 'base64'))
  20. return { success: true, value: outPath, path: outPath }
  21. }
  22. const outUrl = item.url || ''
  23. return { success: true, value: outUrl, path: outUrl || undefined }
  24. } catch (e) {
  25. return { success: false, error: (e && (e.message || String(e))) || 'img2img 异常' }
  26. }
  27. }
  28. module.exports = { executeImg2img }