delete(); return; } $startTime = date('Y-m-d H:i:s'); echo "━━━━━━━━━━ ▶ 文生图任务开始处理━━━━━━━━━━\n"; echo "处理时间:{$startTime}\n"; // 更新日志状态:处理中 if ($logId) { Db::name('image_task_log')->where('id', $logId)->update([ 'status' => 1, 'log' => '文生图处理中', 'update_time' => $startTime ]); } // 拼接原图路径 $old_image_url = rtrim($data['sourceDir'], '/') . '/' . ltrim($data['file_name'], '/'); $list = Db::name("text_to_image") ->where('old_image_url', $old_image_url) ->where('img_name', '<>', '') // ->where('status', 0) ->select(); if (!empty($list)) { $total = count($list); echo "📊 共需处理:{$total} 条记录\n"; foreach ($list as $index => $row) { $currentIndex = $index + 1; $begin = date('Y-m-d H:i:s'); echo "👉 正在处理第 {$currentIndex} 条,ID: {$row['id']}\n"; // 图像生成 $result = $this->textToImage( $data["file_name"], $data["outputDir"], $data["width"], $data["height"], $row["english_description"], $row["img_name"], $data["selectedOption"] ); // 标准化结果文本 if ($result === true || $result === 1 || $result === '成功') { $resultText = '成功'; // 日志状态设置为成功(仅在未提前失败时) if ($logId) { Db::name('image_task_log')->where('id', $logId)->update([ 'status' => 2, 'log' => '文生图处理成功', 'update_time' => date('Y-m-d H:i:s') ]); } } else { $resultText = (string) $result ?: '失败或无返回'; } echo "✅ 处理结果:{$resultText}\n"; echo "完成时间:" . date('Y-m-d H:i:s') . "\n"; echo "文生图已处理完成\n"; // 若包含关键词,日志状态标为失败(-1) if (strpos($resultText, '包含关键词') !== false) { // 命中关键词类错误,状态设为失败 if ($logId) { Db::name('image_task_log')->where('id', $logId)->update([ 'status' => -1, 'log' => $resultText, 'update_time' => date('Y-m-d H:i:s') ]); } } } } // 处理链式任务(如果有) if (!empty($data['chain_next'])) { $nextType = array_shift($data['chain_next']); $data['type'] = $nextType; Queue::push('app\job\ImageArrJob', [ 'task_id' => $data['task_id'], 'data' => [$data] ], 'arrimage'); } $job->delete(); } catch (\Exception $e) { echo "❌ 异常信息: " . $e->getMessage() . "\n"; echo "📄 文件: " . $e->getFile() . "\n"; echo "📍 行号: " . $e->getLine() . "\n"; if ($logId) { Db::name('image_task_log')->where('id', $logId)->update([ 'status' => -1, 'log' => '文生图失败:' . $e->getMessage(), 'update_time' => date('Y-m-d H:i:s') ]); } $job->delete(); } } /** * 任务失败时的处理 */ public function failed($data) { // 记录失败日志或发送通知 echo "ImageJob failed: " . json_encode($data); } /** * 文生图处理函数 * 描述:根据提示词调用图像生成接口,保存图像文件,并更新数据库 */ public function textToImage($fileName, $outputDirRaw, $width, $height, $prompt, $img_name, $selectedOption) { $rootPath = str_replace('\\', '/', ROOT_PATH); $outputDir = rtrim($rootPath . 'public/' . $outputDirRaw, '/') . '/'; $dateDir = date('Y-m-d') . '/'; $fullBaseDir = $outputDir . $dateDir; // 创建输出目录 foreach ([$fullBaseDir, $fullBaseDir . '1024x1024/', $fullBaseDir . "{$width}x{$height}/"] as $dir) { if (!is_dir($dir)) mkdir($dir, 0755, true); } // 获取图像记录 $record = Db::name('text_to_image') ->where('old_image_url', 'like', "%{$fileName}") ->order('id desc') ->find(); Db::name('text_to_image')->where('id', $record['id'])->update([ 'new_image_url' => '', ]); if (!$record) return '没有找到匹配的图像记录'; // 过滤关键词 $prompt = preg_replace('/[\r\n\t]+/', ' ', $prompt); foreach (['几何', 'geometry', 'geometric'] as $keyword) { if (stripos($prompt, $keyword) !== false) { Db::name('text_to_image')->where('id', $record['id'])->update([ 'status' => 3, 'error_msg' => "包含关键词".$keyword, 'update_time' => date('Y-m-d H:i:s') ]); return "包含关键词 - {$keyword}"; } } // AI 图像生成调用 $ai = new AIGatewayService(); $response = $ai->callDalleApi($prompt, $selectedOption); if (isset($response['error'])) { throw new \Exception("❌ 图像生成失败:" . $response['error']['message']); } // 支持 URL 格式(为主)和 base64 $imgData = null; if (isset($response['data'][0]['url'])) { $imgData = @file_get_contents($response['data'][0]['url']); } elseif (isset($response['data'][0]['b64_json'])) { $imgData = base64_decode($response['data'][0]['b64_json']); } if (!$imgData || strlen($imgData) < 1000) { throw new \Exception("❌ 图像内容为空或异常!"); } // 保存文件路径定义 $img_name = mb_substr(preg_replace('/[^\x{4e00}-\x{9fa5}A-Za-z0-9_\- ]/u', '', $img_name), 0, 30); $filename = $img_name . '.png'; $path512 = $fullBaseDir . '1024x1024/' . $filename; $pathCustom = $fullBaseDir . "{$width}x{$height}/" . $filename; // 保存原图 file_put_contents($path512, $imgData); // ➤ 是否执行裁剪(如不想裁剪,可注释以下 try-catch 整块) // try { // $im = imagecreatefromstring($imgData); // if (!$im) throw new \Exception("图像无法解析"); // $srcW = imagesx($im); // $srcH = imagesy($im); // $srcRatio = $srcW / $srcH; // $dstRatio = $width / $height; // if ($srcRatio > $dstRatio) { // $cropW = intval($srcH * $dstRatio); // $cropH = $srcH; // $srcX = intval(($srcW - $cropW) / 2); // $srcY = 0; // } else { // $cropW = $srcW; // $cropH = intval($srcW / $dstRatio); // $srcX = 0; // $srcY = intval(($srcH - $cropH) / 2); // } // $dstImg = imagecreatetruecolor($width, $height); // imagecopyresampled($dstImg, $im, 0, 0, $srcX, $srcY, $width, $height, $cropW, $cropH); // imagepng($dstImg, $pathCustom); // imagedestroy($im); // imagedestroy($dstImg); // } catch (\Throwable $e) { // file_put_contents('/tmp/crop_error.png', $imgData); // throw new \Exception("图像裁剪失败:" . $e->getMessage()); // } // 数据库更新 Db::name('text_to_image')->where('id', $record['id'])->update([ 'new_image_url' => str_replace($rootPath . 'public/', '', $path512), // 注释以下一行则不保存裁剪路径(适配你的配置) // 'custom_image_url' => str_replace($rootPath . 'public/', '', $pathCustom), 'img_name' => $img_name, 'model' => $selectedOption, 'status' => trim($img_name) === '' ? 0 : 1, 'status_name' => "文生图", 'size' => "{$width}x{$height}", 'quality' => 'standard', 'style' => 'vivid', 'error_msg' => '', 'update_time' => date('Y-m-d H:i:s') ]); return "成功"; } }