ImageGenerationController.php 8.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246
  1. <?php
  2. namespace App\Http\Controllers\AIGeneration;
  3. use Illuminate\Routing\Controller as BaseController;
  4. use App\Libs\Utils;
  5. use App\Services\AIGeneration\AIImageGenerationService;
  6. use App\Transformer\AIGeneration\AIGenerationTransformer;
  7. use Illuminate\Http\Request;
  8. use Illuminate\Http\JsonResponse;
  9. use Illuminate\Support\Facades\Validator;
  10. use App\Libs\ApiResponse;
  11. class ImageGenerationController extends BaseController
  12. {
  13. use ApiResponse;
  14. private $aiImageGenerationService;
  15. public function __construct(
  16. AIImageGenerationService $aiImageGenerationService
  17. ) {
  18. $this->aiImageGenerationService = $aiImageGenerationService;
  19. }
  20. /**
  21. * 创建图片生成任务
  22. *
  23. * @param Request $request
  24. * @return JsonResponse
  25. */
  26. public function createTask(Request $request): JsonResponse
  27. {
  28. $data = $request->all();
  29. // 首先验证基本参数
  30. $baseRules = [
  31. 'prompt' => 'required|string|max:2000',
  32. 'width' => 'required|numeric|between:1024,4096',
  33. 'height' => 'required|numeric|between:1024,4096',
  34. 'image_num' => 'required|numeric|between:1,4',
  35. 'scale' => 'required|numeric|between:0,100',
  36. ];
  37. $baseMessages = [
  38. 'prompt.required' => '提示词不能为空',
  39. 'prompt.max' => '提示词不能超过2000个字符',
  40. 'width.required' => '宽不能为空',
  41. 'width.numeric' => '宽必须是数字',
  42. 'width.between' => '宽必须在1024到4096之间',
  43. 'height.required' => '高不能为空',
  44. 'height.numeric' => '高必须是数字',
  45. 'height.between' => '高必须在1024到4096之间',
  46. 'image_num.required' => '生成图片数量不能为空',
  47. 'image_num.numeric' => '生成图片数量必须是数字',
  48. 'image_num.between' => '生成图片数量必须在1到4之间',
  49. 'scale.required' => '缩放比例不能为空',
  50. 'scale.numeric' => '缩放比例必须是数字',
  51. 'scale.between' => '缩放比例必须在0到100之间',
  52. ];
  53. // 根据传入参数决定验证规则
  54. if (isset($data['ref_img_url'])) {
  55. // URL 方式 - 支持单个或多个URL(逗号分隔或数组)
  56. $validationRules = array_merge($baseRules, [
  57. 'ref_img_url' => 'required',
  58. ]);
  59. $validationMessages = array_merge($baseMessages, [
  60. 'ref_img_url.required' => '参考图片URL不能为空',
  61. ]);
  62. } else {
  63. // 上传文件方式 - 支持多个文件
  64. $validationRules = array_merge($baseRules, [
  65. 'ref_img_file' => 'required',
  66. 'ref_img_file.*' => 'image|mimes:jpeg,png|max:4800',
  67. ]);
  68. $validationMessages = array_merge($baseMessages, [
  69. 'ref_img_file.required' => '参考图片不能为空',
  70. 'ref_img_file.*.image' => '参考图片必须是图片文件',
  71. 'ref_img_file.*.mimes' => '参考图片必须是jpeg,png格式',
  72. 'ref_img_file.*.max' => '参考图片大小不能超过4.7MB',
  73. ]);
  74. }
  75. $validator = Validator::make($data, $validationRules, $validationMessages);
  76. if ($validator->fails()) {
  77. Utils::throwError('1002:'.$validator->errors()->first());
  78. }
  79. $refImgUrls = [];
  80. $refImgBase64List = [];
  81. // 处理上传的图片
  82. if ($request->hasFile('ref_img_file')) {
  83. $refImgFiles = is_array($request->file('ref_img_file'))
  84. ? $request->file('ref_img_file')
  85. : [$request->file('ref_img_file')];
  86. foreach ($refImgFiles as $index => $refImgFile) {
  87. // 验证图片分辨率和比例
  88. $refImgInfo = @getimagesize($refImgFile->getPathname());
  89. if (!$refImgInfo) {
  90. Utils::throwError('1003:图片' . ($index + 1) . '格式无效');
  91. }
  92. $refImg = [
  93. 'width' => $refImgInfo[0],
  94. 'height' => $refImgInfo[1],
  95. 'size' => $refImgFile->getSize(),
  96. ];
  97. // 验证图片规格
  98. $this->validateImageSpecs($refImg, $index + 1);
  99. // 上传图片到服务器并获取URL
  100. $filename = randStr(10) . '.' . $refImgFile->getClientOriginalExtension();
  101. $uploaded_url = uploadStreamByTos('image', file_get_contents($refImgFile->getPathname()), $filename);
  102. if (!$uploaded_url) {
  103. Utils::throwError('1003:图片' . ($index + 1) . '保存失败');
  104. }
  105. $refImgUrls[] = $uploaded_url;
  106. }
  107. } else {
  108. // 使用URL方式,支持逗号分隔的字符串或数组
  109. $urls = is_array($data['ref_img_url'])
  110. ? $data['ref_img_url']
  111. : array_map('trim', explode(',', $data['ref_img_url']));
  112. foreach ($urls as $index => $url) {
  113. if (empty($url)) {
  114. continue;
  115. }
  116. // 验证URL格式
  117. if (!filter_var($url, FILTER_VALIDATE_URL)) {
  118. Utils::throwError('1003:图片URL' . ($index + 1) . '格式无效');
  119. }
  120. // 验证远程图片
  121. $refImg = Utils::getRemoteImageInfo($url, true);
  122. if (!$refImg) {
  123. Utils::throwError('1003:图片' . ($index + 1) . '获取失败');
  124. }
  125. // 验证图片规格
  126. $this->validateImageSpecs($refImg, $index + 1);
  127. $refImgUrls[] = $url;
  128. }
  129. }
  130. if (empty($refImgUrls)) {
  131. Utils::throwError('1003:至少需要一张参考图片');
  132. }
  133. // 将处理后的URL存入data(支持多个)
  134. $data['ref_img_urls'] = $refImgUrls;
  135. $data['ref_img_url'] = $refImgUrls[0]; // 保持向后兼容
  136. try {
  137. $task = $this->aiImageGenerationService->createImageGenerationTask($data);
  138. return $this->success(['task_id' => $task->task_id, 'status' => $task->status]);
  139. } catch (\Exception $e) {
  140. Utils::throwError('1001:'.$e->getMessage());
  141. }
  142. }
  143. /**
  144. * 验证图片规格
  145. *
  146. * @param array $refImg
  147. * @param int $index
  148. * @return void
  149. */
  150. private function validateImageSpecs(array $refImg, int $index): void
  151. {
  152. // 判断图片是否满足以下条件:
  153. // 1.图片文件最大4.7MB
  154. // 2.图片分辨率最大: 4096*4096, 最短边不低于320
  155. // 3.图片长边与短边比例在3以内
  156. if ($refImg['size'] > 4.7 * 1024 * 1024) {
  157. Utils::throwError('1003:图片' . $index . '大小不能超过4.7MB');
  158. }
  159. $minDimension = min($refImg['width'], $refImg['height']);
  160. $maxDimension = max($refImg['width'], $refImg['height']);
  161. if ($maxDimension > 4096 || $minDimension < 320) {
  162. Utils::throwError('1003:图片' . $index . '分辨率不能超过4096*4096,且最短边不能低于320');
  163. }
  164. if ($maxDimension / $minDimension > 3) {
  165. Utils::throwError('1003:图片' . $index . '长边与短边比例不能超过3');
  166. }
  167. }
  168. /**
  169. * 查询任务状态
  170. *
  171. * @param string $taskId
  172. * @return JsonResponse
  173. */
  174. public function taskStatus(string $taskId): JsonResponse
  175. {
  176. $task = \App\Models\MpGeneratePicTask::where('task_id', $taskId)->first();
  177. if (!$task) {
  178. return response()->json([
  179. 'success' => false,
  180. 'message' => '任务不存在'
  181. ], 404);
  182. }
  183. return response()->json([
  184. 'success' => true,
  185. 'data' => [
  186. 'task_id' => $task->task_id,
  187. 'status' => $task->status,
  188. 'result_url' => $task->result_url,
  189. 'error_message' => $task->error_message,
  190. 'created_at' => $task->created_at,
  191. 'started_at' => $task->started_at,
  192. 'completed_at' => $task->completed_at
  193. ]
  194. ]);
  195. }
  196. /**
  197. * 获取任务列表
  198. *
  199. * @param Request $request
  200. * @return mixed
  201. */
  202. public function taskList(Request $request)
  203. {
  204. $data = $request->all();
  205. $result = $this->aiImageGenerationService->getTaskList($data);
  206. return $this->success($result, [new AIGenerationTransformer(), 'newBuildTaskList']);
  207. }
  208. }