123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990 |
- <?php
- /**
- * @desc 本地适配器
- *
- * @author Tinywan(ShaoBo Wan)
- * @date 2022/3/7 19:54
- */
- declare(strict_types=1);
- namespace app\common\storage;
- use Intervention\Image\ImageManagerStatic as Image;
- use Tinywan\Storage\Adapter\AdapterAbstract;
- use Tinywan\Storage\Exception\StorageException;
- class LocalAdapter extends AdapterAbstract
- {
- /**
- * @desc: 方法描述
- *
- * @author Tinywan(ShaoBo Wan)
- */
- public function uploadFile(array $options = []): array
- {
- $result = [];
- $basePath = $this->config['root'] . $this->config['dirname'] . DIRECTORY_SEPARATOR;
- if (!$this->createDir($basePath)) {
- throw new StorageException('文件夹创建失败,请核查是否有对应权限。');
- }
- if (!$this->createDir($basePath . '/thumb')) {
- throw new StorageException('文件夹创建失败,请核查是否有对应权限。');
- }
- $baseUrl = $this->config['domain'] . $this->config['uri'] . str_replace(DIRECTORY_SEPARATOR, '/', $this->config['dirname']) . DIRECTORY_SEPARATOR;
- foreach ($this->files as $key => $file) {
- // 缩略
- $image = Image::make($file);
- $uniqueId = hash_file($this->algo, $file->getPathname());
- $saveFilename = $uniqueId . '.' . $file->getUploadExtension();
- $originSavePath = $basePath . $saveFilename;
- $thumbSavePath = $basePath . 'thumb' . DIRECTORY_SEPARATOR . $saveFilename;
- $temp = [
- 'key' => $key,
- 'origin_name' => $file->getUploadName(),
- 'save_name' => $saveFilename,
- 'save_path' => $thumbSavePath,
- 'url' => $baseUrl . 'thumb' . DIRECTORY_SEPARATOR . $saveFilename,
- 'unique_id' => $uniqueId,
- 'size' => $file->getSize(),
- 'mime_type' => $file->getUploadMineType(),
- 'extension' => $file->getUploadExtension(),
- ];
- // 保存原图
- $file->move($originSavePath);
- // 保存缩略图
- $imgWidth = $image->width();
- $imgHeight = $image->height();
- $rate = round($imgWidth / 200, 2);
- $height = intval($imgHeight / $rate);
- $image = $image->resize(200, $height);
- $encoded = $image->encode('jpg');
- $encoded->save($thumbSavePath);
- // $file->move($savePath);
- array_push($result, $temp);
- }
- return $result;
- }
- /**
- * @desc: createDir 描述
- */
- protected function createDir(string $path): bool
- {
- if (is_dir($path)) {
- return true;
- }
- $parent = dirname($path);
- if (!is_dir($parent)) {
- if (!$this->createDir($parent)) {
- return false;
- }
- }
- return mkdir($path);
- }
- }
|