Facility.php 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466
  1. <?php
  2. namespace app\api\controller;
  3. use app\common\controller\Api;
  4. use think\Db;
  5. use think\Request;
  6. class Facility extends Api
  7. {
  8. protected $noNeedLogin = ['*'];
  9. protected $noNeedRight = ['*'];
  10. public function packImagess()
  11. {
  12. try {
  13. $params = $this->request->post();
  14. $paths = $params['paths'] ?? [];
  15. if (empty($paths) || !is_array($paths)) {
  16. return json(['code' => 1, 'msg' => '路径参数不能为空或格式不正确']);
  17. }
  18. // 设置基础路径和压缩目录路径
  19. $basePath = ROOT_PATH . 'public/';
  20. $zipDir = $basePath . 'uploads/operate/ai/zip/';
  21. if (!is_dir($zipDir)) {
  22. mkdir($zipDir, 0755, true);
  23. }
  24. // 压缩包文件名及完整路径
  25. $fileName = 'images_' . date('Ymd_His') . '.zip';
  26. $zipPath = $zipDir . $fileName;
  27. // 创建 Zip 文件
  28. $zip = new \ZipArchive();
  29. if ($zip->open($zipPath, \ZipArchive::CREATE) !== TRUE) {
  30. return json(['code' => 1, 'msg' => '无法创建压缩包']);
  31. }
  32. // 添加文件到压缩包
  33. $addCount = 0;
  34. foreach ($paths as $relativePath) {
  35. $relativePath = ltrim($relativePath, '/');
  36. $fullPath = $basePath . $relativePath;
  37. if (file_exists($fullPath)) {
  38. $zip->addFile($fullPath, basename($fullPath)); // 仅保存文件名
  39. $addCount++;
  40. }
  41. }
  42. $zip->close();
  43. if ($addCount === 0) {
  44. return json(['code' => 1, 'msg' => '未找到有效图片,未生成压缩包']);
  45. }
  46. // 返回下载地址(注意路径与保存路径一致)
  47. $downloadUrl = request()->domain() . '/uploads/operate/ai/zip/' . $fileName;
  48. return json([
  49. 'code' => 0,
  50. 'msg' => '打包成功',
  51. 'download_url' => $downloadUrl
  52. ]);
  53. } catch (\Exception $e) {
  54. return json([
  55. 'code' => 1,
  56. 'msg' => '异常错误:' . $e->getMessage()
  57. ]);
  58. }
  59. }
  60. public function getlsit()
  61. {
  62. // 获取前端传入的图片路径参数
  63. $params = $this->request->param('path', '');
  64. // 查询数据库
  65. $res = Db::name('text_to_image')->alias('b')
  66. ->field('b.chinese_description,b.english_description,b.new_image_url,b.custom_image_url,b.size,b.old_image_url,b.img_name')
  67. ->where('old_image_url', $params)
  68. ->where('img_name', '<>', '')
  69. // ->where('custom_image_url', '<>', '')
  70. // ->where('status', 1)
  71. ->order('b.id desc')
  72. ->select();
  73. return json(['code' => 0, 'msg' => '查询成功', 'data' => $res,'count'=>count($res)]);
  74. }
  75. //获取指定目录所有图片
  76. public function getPreviewimg()
  77. {
  78. $page = (int)$this->request->param('page', 1);
  79. $limit = (int)$this->request->param('limit', 50);
  80. $status = $this->request->param('status', '');
  81. $relativePath = $this->request->param('path', '');
  82. $basePath = ROOT_PATH . 'public/';
  83. $fullPath = $basePath . $relativePath;
  84. if (!is_dir($fullPath)) {
  85. return json(['code' => 1, 'msg' => '目录不存在']);
  86. }
  87. // 1. 获取所有图片路径(不再全部加载到内存)
  88. $allImages = glob($fullPath . '/*.{jpg,jpeg,png}', GLOB_BRACE);
  89. if (empty($allImages)) {
  90. return json(['code' => 0, 'msg' => '暂无图片', 'data' => [], 'total' => 0]);
  91. }
  92. // ✅ 加入排序:按照创建时间从新到旧
  93. usort($allImages, function ($a, $b) {
  94. return filectime($b) - filectime($a);
  95. });
  96. // 构建相对路径数组
  97. $relativeImages = array_map(function ($imgPath) use ($basePath) {
  98. return str_replace($basePath, '', $imgPath);
  99. }, $allImages);
  100. // 2. 提前构建是否已出图map
  101. $dbRecords = Db::name('text_to_image')
  102. ->whereIn('old_image_url', $relativeImages)
  103. ->where('img_name', '<>', '')
  104. ->where('custom_image_url', '<>', '')
  105. ->where('status',1)
  106. ->field('old_image_url,new_image_url,custom_image_url,chinese_description,english_description,img_name')
  107. ->select();
  108. $processedMap = [];
  109. foreach ($dbRecords as $item) {
  110. $processedMap[$item['old_image_url']] = $item;
  111. }
  112. // 3. 提前获取 same_count 的统计
  113. $sameCountMap = Db::name('text_to_image')
  114. ->whereIn('old_image_url', $relativeImages)
  115. ->where('img_name', '<>', '')
  116. ->where('custom_image_url', '<>', '')
  117. ->group('old_image_url')
  118. ->where('status',1)
  119. ->column('count(*) as cnt', 'old_image_url');
  120. // 4. 构造最终筛选数据(分页前进行状态筛选)
  121. $filtered = [];
  122. foreach ($allImages as $imgPath) {
  123. $relative = str_replace($basePath, '', $imgPath);
  124. $processed = $processedMap[$relative] ?? null;
  125. $isProcessed = $processed ? 1 : 0;
  126. // 状态过滤
  127. if ($status === 'processed' && !$isProcessed) continue;
  128. if ($status === 'unprocessed' && $isProcessed) continue;
  129. $info = @getimagesize($imgPath); // 加@防止报错
  130. $sizeKB = round(filesize($imgPath) / 1024, 2);
  131. $ctime = date('Y-m-d H:i:s', filectime($imgPath));
  132. $filtered[] = [
  133. 'path' => $relative,
  134. 'width' => $info[0] ?? 0,
  135. 'height' => $info[1] ?? 0,
  136. 'size_kb' => $sizeKB,
  137. 'created_time' => $ctime,
  138. 'img_name' => $processed['img_name'] ?? '',
  139. 'is_processed' => $isProcessed,
  140. 'new_image_url' => $processed['new_image_url'] ?? '',
  141. 'custom_image_url' => $processed['custom_image_url'] ?? '',
  142. 'chinese_description' => ($processed['chinese_description'] ?? '') . ($processed['english_description'] ?? ''),
  143. 'english_description' => ($processed['english_description'] ?? '') . ($processed['english_description'] ?? ''),
  144. 'same_count' => $sameCountMap[$relative] ?? 0
  145. ];
  146. }
  147. // 5. 手动分页(对少量已筛选后的数据)
  148. $total = count($filtered);
  149. $pagedData = array_slice($filtered, ($page - 1) * $limit, $limit);
  150. foreach ($pagedData as $index => &$item) {
  151. $item['id'] = ($page - 1) * $limit + $index + 1;
  152. }
  153. return json([
  154. 'code' => 0,
  155. 'msg' => '获取成功',
  156. 'data' => $pagedData,
  157. 'total' => $total,
  158. 'page' => $page,
  159. 'limit' => $limit
  160. ]);
  161. }
  162. /**
  163. * 获取原图目录及每个目录下的图片数量
  164. */
  165. public function getPreviewSubDirs()
  166. {
  167. $baseDir = rtrim(str_replace('\\', '/', ROOT_PATH), '/') . '/public/uploads/operate/ai/Preview';
  168. $baseRelativePath = 'uploads/operate/ai/Preview';
  169. if (!is_dir($baseDir)) {
  170. return json(['code' => 1, 'msg' => '目录不存在']);
  171. }
  172. $dirs = [];
  173. $index = 1;
  174. /**
  175. * 递归扫描目录,提取含图片的子目录信息
  176. */
  177. $scanDir = function ($dirPath, $relativePath) use (&$scanDir, &$dirs, &$index) {
  178. $items = scandir($dirPath);
  179. foreach ($items as $item) {
  180. if ($item === '.' || $item === '..') continue;
  181. $fullPath = $dirPath . '/' . $item;
  182. $relPath = $relativePath . '/' . $item;
  183. if (is_dir($fullPath)) {
  184. // 递归子目录
  185. $scanDir($fullPath, $relPath);
  186. } else {
  187. // 匹配图片文件
  188. if (preg_match('/\.(jpg|jpeg|png)$/i', $item)) {
  189. $parentDir = dirname($fullPath);
  190. $relativeDir = dirname($relPath);
  191. $key = md5($parentDir);
  192. if (!isset($dirs[$key])) {
  193. $ctime = filectime($parentDir);
  194. // 数据库统计:已处理图片数量
  195. $hasData = Db::name('text_to_image')
  196. ->where('custom_image_url', '<>', '')
  197. ->where('img_name', '<>', '')
  198. ->whereLike('old_image_url', $relativeDir . '/%')
  199. ->where('status',1)
  200. ->whereNotNull('custom_image_url')
  201. ->count();
  202. // 当前目录下图片数量
  203. $imageFiles = glob($parentDir . '/*.{jpg,jpeg,png}', GLOB_BRACE);
  204. $imageCount = is_array($imageFiles) ? count($imageFiles) : 0;
  205. $dirs[$key] = [
  206. 'id' => $index++,
  207. 'name' => basename($parentDir),
  208. 'count' => $hasData,
  209. 'ctime' => $ctime, // 时间戳,用于排序
  210. 'ctime_text' => date('Y-m-d H:i:s', $ctime), // 格式化日期,用于显示
  211. 'image_count' => $imageCount,
  212. 'new_image_url' => "/uploads/operate/ai/dall-e/",
  213. 'old_image_url' => $relativeDir
  214. ];
  215. }
  216. }
  217. }
  218. }
  219. };
  220. // 执行目录扫描
  221. $scanDir($baseDir, $baseRelativePath);
  222. // 排序:按照创建时间(从新到旧)
  223. $dirList = array_values($dirs);
  224. usort($dirList, function ($a, $b) {
  225. return $b['ctime'] - $a['ctime'];
  226. });
  227. return json([
  228. 'code' => 0,
  229. 'msg' => '获取成功',
  230. 'data' => $dirList
  231. ]);
  232. }
  233. /**
  234. * 图片上传
  235. * @return void
  236. */
  237. // public function getUploadPath()
  238. // {
  239. // // 处理 CORS OPTIONS 预检请求
  240. // if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {
  241. // header('Access-Control-Allow-Origin: *');
  242. // header('Access-Control-Allow-Methods: POST, OPTIONS');
  243. // header('Access-Control-Allow-Headers: Content-Type, Authorization');
  244. // header('Access-Control-Max-Age: 86400');
  245. // exit(204);
  246. // }
  247. //
  248. //// 实际请求必须返回 CORS 头
  249. // header('Access-Control-Allow-Origin: *');
  250. // $today = date('Ymd');
  251. // $basePath = 'uploads/operate/ai/Preview/' . $today;
  252. // $rootBasePath = ROOT_PATH . 'public/' . $basePath;
  253. //
  254. // // 创建当天目录
  255. // if (!is_dir($rootBasePath)) {
  256. // mkdir($rootBasePath, 0755, true);
  257. // }
  258. //
  259. // // 获取子目录索引
  260. // $dirs = array_filter(glob($rootBasePath . '/*'), 'is_dir');
  261. // $usedIndexes = [];
  262. //
  263. // foreach ($dirs as $dirPath) {
  264. // $dirName = basename($dirPath);
  265. // if (preg_match('/^\d{2}$/', $dirName)) {
  266. // $usedIndexes[] = intval($dirName);
  267. // }
  268. // }
  269. //
  270. // $nextIndex = empty($usedIndexes) ? 1 : max($usedIndexes) + 1;
  271. // $subDir = str_pad($nextIndex, 2, '0', STR_PAD_LEFT);
  272. // $relativePath = $basePath . '/' . $subDir;
  273. // $targetPath = ROOT_PATH . 'public/' . $relativePath;
  274. //
  275. // // 创建该批次目录
  276. // if (!is_dir($targetPath)) {
  277. // mkdir($targetPath, 0755, true);
  278. // }
  279. //
  280. // return json([
  281. // 'code' => 0,
  282. // 'msg' => '获取上传路径成功',
  283. // 'data' => [
  284. // 'upload_path' => $relativePath
  285. // ]
  286. // ]);
  287. // }
  288. // public function ImgUpload()
  289. // {
  290. // if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {
  291. // header('Access-Control-Allow-Origin: *');
  292. // header('Access-Control-Allow-Methods: POST, OPTIONS');
  293. // header('Access-Control-Allow-Headers: Content-Type, Authorization');
  294. // header('Access-Control-Max-Age: 86400');
  295. // exit(204);
  296. // }
  297. // header('Access-Control-Allow-Origin: *');
  298. //
  299. // $file = request()->file('image');
  300. // $relativePath = input('post.upload_path');
  301. //
  302. // if (!$file || !$relativePath) {
  303. // return json(['code' => 1, 'msg' => '缺少上传文件或路径参数']);
  304. // }
  305. //
  306. // $targetPath = ROOT_PATH . 'public/' . $relativePath;
  307. //
  308. // if (!is_dir($targetPath)) {
  309. // mkdir($targetPath, 0755, true);
  310. // }
  311. //
  312. // $tmpFilePath = $file->getPathname();
  313. // $extension = pathinfo($file->getInfo('name'), PATHINFO_EXTENSION);
  314. // $hashName = hash_file('md5', $tmpFilePath);
  315. // $newFileName = $hashName . '.' . $extension;
  316. //
  317. // $info = $file->validate(['size' => 10 * 1024 * 1024, 'ext' => 'jpg,jpeg,png'])
  318. // ->move($targetPath, $newFileName);
  319. //
  320. // if ($info) {
  321. // $imageUrl = $relativePath . '/' . str_replace('\\', '/', $newFileName);
  322. // return json(['code' => 0, 'msg' => '上传成功', 'data' => ['url' => $imageUrl]]);
  323. // } else {
  324. // return json(['code' => 1, 'msg' => '上传失败', 'data' => $file->getError()]);
  325. // }
  326. // }
  327. public function ImgUpload()
  328. {
  329. // 处理 CORS OPTIONS 预检请求
  330. if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {
  331. header('Access-Control-Allow-Origin: *');
  332. header('Access-Control-Allow-Methods: POST, OPTIONS');
  333. header('Access-Control-Allow-Headers: Content-Type, Authorization');
  334. header('Access-Control-Max-Age: 86400');
  335. exit(204);
  336. }
  337. // 实际请求必须返回 CORS 头
  338. header('Access-Control-Allow-Origin: *');
  339. // 获取上传的文件
  340. $file = request()->file('image');
  341. if ($file) {
  342. // 指定目标目录(你想上传到的目录)
  343. $targetPath = ROOT_PATH . 'public' . DS . 'uploads' . DS . 'operate' . DS . 'ai' . DS . 'Preview';
  344. // 若目录不存在则创建
  345. if (!is_dir($targetPath)) {
  346. mkdir($targetPath, 0755, true);
  347. }
  348. // 移动文件到指定目录,并验证大小/格式
  349. $info = $file->validate([
  350. 'size' => 10485760, // 最大10MB
  351. 'ext' => 'jpg,png'
  352. ])->move($targetPath);
  353. if ($info) {
  354. $fileName = $info->getSaveName();
  355. $imageUrl = '/uploads/operate/ai/Preview/' . str_replace('\\', '/', $fileName);
  356. return json(['code' => 0, 'msg' => '成功', 'data' => ['url' => $imageUrl]]);
  357. } else {
  358. $res = $file->getError();
  359. return json(['code' => 1, 'msg' => '失败', 'data' => $res]);
  360. }
  361. }
  362. return json(['code' => 1, 'msg' => '没有文件上传', 'data' => null]);
  363. }
  364. /**
  365. * 模版
  366. */
  367. public function Template(){
  368. $Template = Db::name("template")->find();
  369. return json([
  370. 'code' => 0,
  371. 'msg' => '模版',
  372. 'data' => $Template
  373. ]);
  374. }
  375. /**
  376. * 更新模版
  377. */
  378. public function updatetemplate(){
  379. if (Request::instance()->isPost() == false){
  380. $this->error('非法请求');
  381. }
  382. $params = Request::instance()->post();
  383. // 验证传入的参数是否存在,避免空值
  384. if (empty($params['textareaContent']) || empty($params['width']) || empty($params['height'])) {
  385. return json(['code' => 1, 'msg' => '参数缺失']);
  386. }
  387. // 更新模板数据
  388. $Template = Db::name("template")
  389. ->where('id', 1) // 假设模板 ID 是 1,需根据实际情况修改
  390. ->update([
  391. 'content' => $params['textareaContent'], // 更新图生文模版内容
  392. 'width' => $params['width'], // 更新宽度
  393. 'height' => $params['height'], // 更新宽度
  394. ]);
  395. // 判断数据库更新是否成功
  396. if ($Template){
  397. return json(['code' => 0, 'msg' => '成功']);
  398. }else{
  399. return json(['code' => 1, 'msg' => '失败']);
  400. }
  401. }
  402. }