GoodsThumbCommand.php 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. <?php
  2. namespace app\command;
  3. use app\model\Goods;
  4. use Intervention\Image\Gd\Driver;
  5. use Intervention\Image\ImageManager;
  6. use Intervention\Image\ImageManagerStatic;
  7. use Symfony\Component\Console\Command\Command;
  8. use Symfony\Component\Console\Input\InputInterface;
  9. use Symfony\Component\Console\Input\InputOption;
  10. use Symfony\Component\Console\Input\InputArgument;
  11. use Symfony\Component\Console\Output\OutputInterface;
  12. use Tinywan\Storage\Exception\StorageException;
  13. class GoodsThumbCommand extends Command
  14. {
  15. protected static $defaultName = 'GoodsThumbCommand';
  16. protected static $defaultDescription = 'GoodsThumbCommand';
  17. /**
  18. * @return void
  19. */
  20. protected function configure()
  21. {
  22. $this->addArgument('name', InputArgument::OPTIONAL, '商品主图片批量缩略');
  23. }
  24. /**
  25. * @param InputInterface $input
  26. * @param OutputInterface $output
  27. * @return int
  28. */
  29. protected function execute(InputInterface $input, OutputInterface $output): int
  30. {
  31. $goods = Goods::select('goods_id','goods_cover')->limit(1)->get()->toArray();
  32. foreach ($goods as $good){
  33. if (!file_exists(public_path($good['goods_cover']))){
  34. echo "【".$good['goods_id']."】源文件不存在,跳过 \n";
  35. continue;
  36. }
  37. $fileNameArray = explode(DIRECTORY_SEPARATOR,$good['goods_cover']);
  38. $two = $fileNameArray[count($fileNameArray)-2];
  39. if ($two == 'thumb'){
  40. echo "【".$good['goods_id']."】已存在,跳过 \n";
  41. continue;
  42. }
  43. array_splice($fileNameArray,-1,0,'thumb');
  44. $thumbPath = public_path(ltrim(implode(DIRECTORY_SEPARATOR,$fileNameArray),DIRECTORY_SEPARATOR));
  45. if (file_exists($thumbPath)){
  46. echo "【".$good['goods_id']."】缩略图已存在,跳过 \n";
  47. continue;
  48. }
  49. $path = array_slice($fileNameArray,0,-1);
  50. $pathStr = public_path(ltrim(implode(DIRECTORY_SEPARATOR,$path),DIRECTORY_SEPARATOR));
  51. if (!is_dir($pathStr) && !mkdir($pathStr, 0755, true)){
  52. throw new StorageException('文件夹创建失败,请核查是否有对应权限。');
  53. }
  54. $image = ImageManagerStatic::make(public_path($good['goods_cover']));
  55. $imgWidth = $image->width();
  56. $imgHeight = $image->height();
  57. $rate = round($imgWidth / 200, 2);
  58. $height = intval($imgHeight / $rate);
  59. $image = $image->resize(200, $height);
  60. $encoded = $image->encode('jpg');
  61. $encoded->save($thumbPath);
  62. Goods::where('goods_id',$good['goods_id'])->update(['goods_cover'=>implode(DIRECTORY_SEPARATOR,$fileNameArray)]);
  63. echo "【".$good['goods_id']."】已完成 \n";
  64. }
  65. return self::SUCCESS;
  66. }
  67. }