ImageController.php 2.6 KB
<?php

namespace App\Http\Controllers;

use App\Enums\Common\Code;
use App\Models\Image as ImageModel;
use Faker\Provider\Image;
use Illuminate\Http\Exceptions\HttpResponseException;
use Illuminate\Http\JsonResponse;

class ImageController
{

    public function index($hash = '', $w = 0 ,$h = 0){
        if (isset($_SERVER['HTTP_IF_MODIFIED_SINCE']) || isset($_SERVER['HTTP_IF_NONE_MATCH'])) {
            header("HTTP/1.1 304 Not Modified");
            exit;
        }
        $imageModel = new ImageModel();
        $info = $imageModel->read(['hash'=>$hash]);
        if ($info === false) {
            $this->response('指定图片不存在!', 404);
        }
        $path = './../'.$info['path'];
        if (!is_file($path)) {
            $this->response('指定图片已被系统删除!', 404,$path);
        }
        $content = '';
        $last_modified_time = gmdate(time() + ((30 * 60 * 60 * 24))) . " GMT";
        $header = str_replace(['%Expires%', "%etag%", '%Last-Modified%'], [$last_modified_time, $hash . ':' . $w . '_' . $h . '_' . 2, $last_modified_time], $this->config['header_cache']);
        if ($w > 0 && $h > 0) {
            $path = $this->cacheImage($info, $w, $h, 2);
            $content = file_get_contents($path);
            $header['Content-Length'] = strlen($content);
        } else {
            $content = file_get_contents($path);
            $header['Content-Length'] = $info['size'];
        }
        return response($content, 200, $header);
    }

    /**
     * 生成缩略图缓存
     * @param type $info
     * @param type $w
     * @param type $h
     * @return string
     */
    private function cacheImage($info, $w, $h, $type = 2) {
        $thumbnailPath = './../uploads/image/';
        $thumbnailImage = Image::make($info)
            ->fit($w, $h, function ($constraint) {
                $constraint->upsize();
            });

        $thumbnailImage->save($thumbnailPath);
        return $thumbnailPath;
        return;
    }

    /**
     * @name 统一返回参数
     * @return JsonResponse
     * @author :liyuhang
     * @method
     */
    public function response($msg = null,string $code = Code::SUCCESS,$data = [],$result_code = 200,$type = 'application/json'): JsonResponse
    {
        $code = Code::fromValue($code);
        $result = [
            'msg' => $msg == ' ' ? $code->description : $msg,
            'code' => $code->value,
            'data' => $this->_extents($data),
        ];
        $this->header['Content-Type'] = $type;
        $this->header['token'] = $this->token;
        $response =  response($result,$result_code,$this->header);;
        throw new HttpResponseException($response);
    }
}