tp8结合Intervention Image(libvips)生成缩略图

libvips的优势:libvips is a fast, low-memory image processing library that outperforms the standard PHP image extensions GD and Imagick;

前提条件:php8.3的FFI功能已安装且开放;libvips已安装,安装教程请看我之前的教程;php的版本不得低于8.3;

bash 复制代码
composer require intervention/image
composer require intervention/image-driver-vips
php 复制代码
use Intervention\Image\ImageManager;
use Intervention\Image\Drivers\Vips\Driver as VipsDriver;

class Index
{
    /**
     * libvips 等比例缩放测试
     */
    public function vips()
    {
        try {
            // 创建 Vips 图片管理器
            $manager = ImageManager::usingDriver(VipsDriver::class);

            // 原图片
            $imagePath = public_path('storage') . 'test.jpg';

            // 输出图片
            $outputPath = public_path('storage') . 'test_300.jpg';

            // 判断原图片是否存在
            if (!is_file($imagePath)) {
                return json([
                    'code' => 1,
                    'msg'  => '原图片不存在',
                    'path' => $imagePath,
                ]);
            }

            // 读取图片
            $image = $manager->decodePath($imagePath);

            // 原始尺寸
            $originalWidth  = $image->width();
            $originalHeight = $image->height();

            // 按高度等比例缩放
            $image->scale(height: 300);

            // 缩放后的尺寸
            $newWidth  = $image->width();
            $newHeight = $image->height();

            // 保存成 WebP
            $encoded = $image->encodeUsingFileExtension(
                'jpg',
                quality: 90
            );

            // 保存
            $encoded->save($outputPath);

            return json([
                'code' => 0,
                'msg'  => 'libvips 等比例缩放成功',
                'data' => [
                    'driver' => VipsDriver::class,

                    'original' => [
                        'width'  => $originalWidth,
                        'height' => $originalHeight,
                    ],

                    'scaled' => [
                        'width'  => $newWidth,
                        'height' => $newHeight,
                    ],

                    'input'  => $imagePath,
                    'output' => $outputPath,
                    'url'    => '/storage/test_300.webp',
                ],
            ]);

        } catch (\Throwable $e) {
            return json([
                'code' => 1,
                'msg'  => '处理失败',
                'error' => $e->getMessage(),
                'file'  => $e->getFile(),
                'line'  => $e->getLine(),
            ]);
        }
    }
}
相关推荐
总有刁民想爱朕ha7 个月前
PixMark —— 免费开源的一体化图片处理工具箱,批量水印 + 图片转视频一键搞定
开源·图片生成视频·pixmark·图片加水印