Facility.php 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465
  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. 'same_count' => $sameCountMap[$relative] ?? 0
  144. ];
  145. }
  146. // 5. 手动分页(对少量已筛选后的数据)
  147. $total = count($filtered);
  148. $pagedData = array_slice($filtered, ($page - 1) * $limit, $limit);
  149. foreach ($pagedData as $index => &$item) {
  150. $item['id'] = ($page - 1) * $limit + $index + 1;
  151. }
  152. return json([
  153. 'code' => 0,
  154. 'msg' => '获取成功',
  155. 'data' => $pagedData,
  156. 'total' => $total,
  157. 'page' => $page,
  158. 'limit' => $limit
  159. ]);
  160. }
  161. /**
  162. * 获取原图目录及每个目录下的图片数量
  163. */
  164. public function getPreviewSubDirs()
  165. {
  166. $baseDir = rtrim(str_replace('\\', '/', ROOT_PATH), '/') . '/public/uploads/operate/ai/Preview';
  167. $baseRelativePath = 'uploads/operate/ai/Preview';
  168. if (!is_dir($baseDir)) {
  169. return json(['code' => 1, 'msg' => '目录不存在']);
  170. }
  171. $dirs = [];
  172. $index = 1;
  173. /**
  174. * 递归扫描目录,提取含图片的子目录信息
  175. */
  176. $scanDir = function ($dirPath, $relativePath) use (&$scanDir, &$dirs, &$index) {
  177. $items = scandir($dirPath);
  178. foreach ($items as $item) {
  179. if ($item === '.' || $item === '..') continue;
  180. $fullPath = $dirPath . '/' . $item;
  181. $relPath = $relativePath . '/' . $item;
  182. if (is_dir($fullPath)) {
  183. // 递归子目录
  184. $scanDir($fullPath, $relPath);
  185. } else {
  186. // 匹配图片文件
  187. if (preg_match('/\.(jpg|jpeg|png)$/i', $item)) {
  188. $parentDir = dirname($fullPath);
  189. $relativeDir = dirname($relPath);
  190. $key = md5($parentDir);
  191. if (!isset($dirs[$key])) {
  192. $ctime = filectime($parentDir);
  193. // 数据库统计:已处理图片数量
  194. $hasData = Db::name('text_to_image')
  195. ->where('custom_image_url', '<>', '')
  196. ->where('img_name', '<>', '')
  197. ->whereLike('old_image_url', $relativeDir . '/%')
  198. ->where('status',1)
  199. ->whereNotNull('custom_image_url')
  200. ->count();
  201. // 当前目录下图片数量
  202. $imageFiles = glob($parentDir . '/*.{jpg,jpeg,png}', GLOB_BRACE);
  203. $imageCount = is_array($imageFiles) ? count($imageFiles) : 0;
  204. $dirs[$key] = [
  205. 'id' => $index++,
  206. 'name' => basename($parentDir),
  207. 'count' => $hasData,
  208. 'ctime' => $ctime, // 时间戳,用于排序
  209. 'ctime_text' => date('Y-m-d H:i:s', $ctime), // 格式化日期,用于显示
  210. 'image_count' => $imageCount,
  211. 'new_image_url' => "/uploads/operate/ai/dall-e/",
  212. 'old_image_url' => $relativeDir
  213. ];
  214. }
  215. }
  216. }
  217. }
  218. };
  219. // 执行目录扫描
  220. $scanDir($baseDir, $baseRelativePath);
  221. // 排序:按照创建时间(从新到旧)
  222. $dirList = array_values($dirs);
  223. usort($dirList, function ($a, $b) {
  224. return $b['ctime'] - $a['ctime'];
  225. });
  226. return json([
  227. 'code' => 0,
  228. 'msg' => '获取成功',
  229. 'data' => $dirList
  230. ]);
  231. }
  232. /**
  233. * 图片上传
  234. * @return void
  235. */
  236. // public function getUploadPath()
  237. // {
  238. // // 处理 CORS OPTIONS 预检请求
  239. // if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {
  240. // header('Access-Control-Allow-Origin: *');
  241. // header('Access-Control-Allow-Methods: POST, OPTIONS');
  242. // header('Access-Control-Allow-Headers: Content-Type, Authorization');
  243. // header('Access-Control-Max-Age: 86400');
  244. // exit(204);
  245. // }
  246. //
  247. //// 实际请求必须返回 CORS 头
  248. // header('Access-Control-Allow-Origin: *');
  249. // $today = date('Ymd');
  250. // $basePath = 'uploads/operate/ai/Preview/' . $today;
  251. // $rootBasePath = ROOT_PATH . 'public/' . $basePath;
  252. //
  253. // // 创建当天目录
  254. // if (!is_dir($rootBasePath)) {
  255. // mkdir($rootBasePath, 0755, true);
  256. // }
  257. //
  258. // // 获取子目录索引
  259. // $dirs = array_filter(glob($rootBasePath . '/*'), 'is_dir');
  260. // $usedIndexes = [];
  261. //
  262. // foreach ($dirs as $dirPath) {
  263. // $dirName = basename($dirPath);
  264. // if (preg_match('/^\d{2}$/', $dirName)) {
  265. // $usedIndexes[] = intval($dirName);
  266. // }
  267. // }
  268. //
  269. // $nextIndex = empty($usedIndexes) ? 1 : max($usedIndexes) + 1;
  270. // $subDir = str_pad($nextIndex, 2, '0', STR_PAD_LEFT);
  271. // $relativePath = $basePath . '/' . $subDir;
  272. // $targetPath = ROOT_PATH . 'public/' . $relativePath;
  273. //
  274. // // 创建该批次目录
  275. // if (!is_dir($targetPath)) {
  276. // mkdir($targetPath, 0755, true);
  277. // }
  278. //
  279. // return json([
  280. // 'code' => 0,
  281. // 'msg' => '获取上传路径成功',
  282. // 'data' => [
  283. // 'upload_path' => $relativePath
  284. // ]
  285. // ]);
  286. // }
  287. // public function ImgUpload()
  288. // {
  289. // if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {
  290. // header('Access-Control-Allow-Origin: *');
  291. // header('Access-Control-Allow-Methods: POST, OPTIONS');
  292. // header('Access-Control-Allow-Headers: Content-Type, Authorization');
  293. // header('Access-Control-Max-Age: 86400');
  294. // exit(204);
  295. // }
  296. // header('Access-Control-Allow-Origin: *');
  297. //
  298. // $file = request()->file('image');
  299. // $relativePath = input('post.upload_path');
  300. //
  301. // if (!$file || !$relativePath) {
  302. // return json(['code' => 1, 'msg' => '缺少上传文件或路径参数']);
  303. // }
  304. //
  305. // $targetPath = ROOT_PATH . 'public/' . $relativePath;
  306. //
  307. // if (!is_dir($targetPath)) {
  308. // mkdir($targetPath, 0755, true);
  309. // }
  310. //
  311. // $tmpFilePath = $file->getPathname();
  312. // $extension = pathinfo($file->getInfo('name'), PATHINFO_EXTENSION);
  313. // $hashName = hash_file('md5', $tmpFilePath);
  314. // $newFileName = $hashName . '.' . $extension;
  315. //
  316. // $info = $file->validate(['size' => 10 * 1024 * 1024, 'ext' => 'jpg,jpeg,png'])
  317. // ->move($targetPath, $newFileName);
  318. //
  319. // if ($info) {
  320. // $imageUrl = $relativePath . '/' . str_replace('\\', '/', $newFileName);
  321. // return json(['code' => 0, 'msg' => '上传成功', 'data' => ['url' => $imageUrl]]);
  322. // } else {
  323. // return json(['code' => 1, 'msg' => '上传失败', 'data' => $file->getError()]);
  324. // }
  325. // }
  326. public function ImgUpload()
  327. {
  328. // 处理 CORS OPTIONS 预检请求
  329. if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {
  330. header('Access-Control-Allow-Origin: *');
  331. header('Access-Control-Allow-Methods: POST, OPTIONS');
  332. header('Access-Control-Allow-Headers: Content-Type, Authorization');
  333. header('Access-Control-Max-Age: 86400');
  334. exit(204);
  335. }
  336. // 实际请求必须返回 CORS 头
  337. header('Access-Control-Allow-Origin: *');
  338. // 获取上传的文件
  339. $file = request()->file('image');
  340. if ($file) {
  341. // 指定目标目录(你想上传到的目录)
  342. $targetPath = ROOT_PATH . 'public' . DS . 'uploads' . DS . 'operate' . DS . 'ai' . DS . 'Preview';
  343. // 若目录不存在则创建
  344. if (!is_dir($targetPath)) {
  345. mkdir($targetPath, 0755, true);
  346. }
  347. // 移动文件到指定目录,并验证大小/格式
  348. $info = $file->validate([
  349. 'size' => 10485760, // 最大10MB
  350. 'ext' => 'jpg,png'
  351. ])->move($targetPath);
  352. if ($info) {
  353. $fileName = $info->getSaveName();
  354. $imageUrl = '/uploads/operate/ai/Preview/' . str_replace('\\', '/', $fileName);
  355. return json(['code' => 0, 'msg' => '成功', 'data' => ['url' => $imageUrl]]);
  356. } else {
  357. $res = $file->getError();
  358. return json(['code' => 1, 'msg' => '失败', 'data' => $res]);
  359. }
  360. }
  361. return json(['code' => 1, 'msg' => '没有文件上传', 'data' => null]);
  362. }
  363. /**
  364. * 模版
  365. */
  366. public function Template(){
  367. $Template = Db::name("template")->find();
  368. return json([
  369. 'code' => 0,
  370. 'msg' => '模版',
  371. 'data' => $Template
  372. ]);
  373. }
  374. /**
  375. * 更新模版
  376. */
  377. public function updatetemplate(){
  378. if (Request::instance()->isPost() == false){
  379. $this->error('非法请求');
  380. }
  381. $params = Request::instance()->post();
  382. // 验证传入的参数是否存在,避免空值
  383. if (empty($params['textareaContent']) || empty($params['width']) || empty($params['height'])) {
  384. return json(['code' => 1, 'msg' => '参数缺失']);
  385. }
  386. // 更新模板数据
  387. $Template = Db::name("template")
  388. ->where('id', 1) // 假设模板 ID 是 1,需根据实际情况修改
  389. ->update([
  390. 'content' => $params['textareaContent'], // 更新图生文模版内容
  391. 'width' => $params['width'], // 更新宽度
  392. 'height' => $params['height'], // 更新宽度
  393. ]);
  394. // 判断数据库更新是否成功
  395. if ($Template){
  396. return json(['code' => 0, 'msg' => '成功']);
  397. }else{
  398. return json(['code' => 1, 'msg' => '失败']);
  399. }
  400. }
  401. }