当前位置: 首页 > 工具软件 > PHPixie > 使用案例 >

PHP phpixie/image 实现图片裁剪压缩不需保存,直接在浏览器打开显示

赵佐
2023-12-01

场景说明

最开始使用的是七牛云存储,它自带了图片裁剪功能,也就是说我们只要上传一张原图就行,之后可以传入不同尺寸来访问。由于后面决策调整,商城图片要存在本地服务器磁盘上,这时候每次访问都是请求原图,页面打开很慢,所以需要对图片进行裁剪压缩,还有个附加要求是裁剪后台图片不需要保存到服务器,可在浏览器直接打开。

现在表中存放的路径是 https://xxx.com/storage/adminImg/e24e13952392aacaa65f558c918a791a.jpg

安装扩展

composer require phpixie/image:~3.0 -vvv

删除扩展

composer remove phpixie/image

代码

public function actionIndex()
{
    Header( "Content-type: image/jpeg");

    $url = trim($this->get('url'));
    $width = intval($this->get('w'));
    $height = intval($this->get('h'));

    $root = \Yii::$app->basePath;
    // 解析url
    $url_info = parse_url($url);
    // 获得文件目录
    $path = $url_info['path'] ?? '';
    // 拼接文件绝对路径
    $file_full_path = $root .'/web/'. $path;

    // 如果在本地磁盘没找到,那就直接返回
    if (!file_exists($file_full_path)) {
        $image = new Image('imagick');
        //$image = new Image();
        $data = file_get_contents($url);
        $img = $image->load($data);
        echo $img->render();
        exit();
    }

    // 默认图片处理驱动为 gd
    $image = new Image('imagick');
    //$image = new Image();
    // 读取图片
    $img = $image->read($file_full_path);
    // 设置图片大小
    if ($width && $height) {
        $img->resize($width, $height);
    }
    elseif ($width) {
        $img->resize($width);
    }
    else {
        $img->resize(null, $height);
    }

    echo $img->render();
    exit();
}

访问示例

https://xxx.com/helper/image/index?url=https%3A%2F%xxxx.com%2Fstorage%2FadminImg%2Fe24e13952392aacaa65f558c918a791a.jpg&w=200
 类似资料: