Home >PHP Framework >ThinkPHP >How to add dynamic cropping function of image size in ThinkPHP project

How to add dynamic cropping function of image size in ThinkPHP project

藏色散人
藏色散人forward
2021-04-08 16:18:032392browse

The following tutorial column will introduce to you the dynamic cropping function of image size in the ThinkPHP project. I hope it will be helpful to friends who need it!

Add the dynamic cropping function of image size in the ThinkPHP project

How to add dynamic cropping function of image size in ThinkPHP project

ThinkPHP dynamic cropping and scaling library of images

Attach the project first Address: https://github.com/top-think/think-glide

Glide is an image manipulation library that can help you dynamically generate image content for the browser based on specified parameters, thereby achieving

For dynamic image cropping, watermarking, etc., this library provides some friendly packaging and extensions to Glide, shielding some of the underlying abstractions of the native library so that ThinkPHP users can better add dynamic cropping functions for images in ThinkPHP projects. .

Installation


Execute the following command to install:

$ composer require slince/think-glide
Usage

Quick start

Since the middle has been added since ThinkPHP 5.1.6 function of the software, so use middleware registration in

ThinkPHP 5.1.6 and above versions:

Open the
    application/middleware.php
  • file (if Just create it if it does not exist), register middleware:

    return [
        //...
    
        \Slince\Glide\GlideMiddleware::factory([
            'source' => __DIR__ . '/../img',
        ])
    ];
    This method is relatively simple and recommended;

    ThinkPHP 5.1.0 or above 5.1.6 or below :

    does not support middleware, so the activation process is a bit more complicated. We compromise in the following way:
// 在 /route/route.php 注册下面路由
Route::get('images/:file', 'index/handleImageRequest');

//在控制器 index 里创建action
public function handleImageRequest()
{
    $middleware = \Slince\Glide\GlideMiddleware::factory([
        'source' => App::getRootPath() . '/img',
    ]);
    
    return $middleware(app('request'), function(){
        return app('response');
    });
}
  • source

    is your local image file folder location, assuming there is a picture
  • user.jpg in this directory, open the browser and visit the following link:

    http://youdomain.com/images/user.jpg?w=100&h=100
    to get the reduced picture. Parameter description

    Parameter name

    TypeDescriptionIs it required?sourcestringLocal folder location is cachestringCache file location, default is below NocacheTimestringCache time, example, multiple requests during the cache period will automatically respond with 304NosignKeystringSecure signatureNoonExceptioncallable Exception handling handlerNobaseUrlstringRouting prefix, when the prefix is ​​matched The middleware starts executing, the default is No##Security signatureDoes not enable security signature In this case, the user can adjust the parameters in the query to crop the image by himself. If you do not intend to do this, you can verify it through signKey
    runtime/glide
    2 days
    /images
    ,

    \Slince\Glide\GlideMiddleware::factory([
        'source' => __DIR__ . '/../img',
        'signKey' => 'v-LK4WCdhcfcc%jt*VC2cj%nVpu+xQKvLUA%H86kRVk_4bgG8&CWM#k*'
    ])

    in this case It will be invalid if the user adjusts the parameters by himself; generate a safe URL:

    echo app('glide.url_builder')->getUrl('user.jpg', ['w' => 100, 'h' => 100]);
    
    //你会得到如下链接:/images/user.jpg?w=100&h=100&s=af3dc18fc6bfb2afb521e587c348b904

    Exception handlingIf the user accesses a non-existent picture or does not perform security verification, the system will throw Exception, you can replace the default behavior by onException

    :

    \Slince\Glide\GlideMiddleware::factory([
        'source' => __DIR__ . '/../img',
        'signKey' => 'v-LK4WCdhcfcc%jt*VC2cj%nVpu+xQKvLUA%H86kRVk_4bgG8&CWM#k*',
        'onException' => function(\Exception $exception, $request, $server){
        
            if ($exception instanceof \League\Glide\Signatures\SignatureException) {
                $response = new Response('签名错误', 403);
            } else {
                $response = new Response(sprintf('你访问的资源 "%s" 不存在', $request->path()), 404);
            }
            
            return $response;
        }
    ])

    Note that the closure must return a

    think\Response

    instance; Quick reference

    Not only supports cropping, glide also supports other operations. Just pass the corresponding parameters. Refer here to view the supported parameters: http://glide.thephpleague.com/1.0/api/ quick-reference/

    Related recommendations:

    The latest 10 thinkphp video tutorials

    The above is the detailed content of How to add dynamic cropping function of image size in ThinkPHP project. For more information, please follow other related articles on the PHP Chinese website!

    Statement:
    This article is reproduced at:segmentfault.com. If there is any infringement, please contact admin@php.cn delete