首页 » PHP » 正文

Guzzle 和 PSR-7在Intervention Image中的应用

2018-5-16 ·  2,970 views  ·  0 replies 
先了解下PSR-7

HTTP 消息是 Web 技术发展的基础。浏览器或 HTTP 客户端如 curl 生成发送 HTTP 请求消息到 Web 服务器,Web 服务器响应 HTTP 请求。服务端的代码接受 HTTP 请求消息后返回 HTTP 响应消息。
通常 HTTP 消息对于终端用户来说是不可见的,但是作为 Web 开发者,我们需要知道 HTTP 机制,如何发起、构建、取用还有操纵 HTTP 消息,知道这些原理,以助我们刚好的完成开发任务,无论这个任务是发起一个 HTTP 请求,或者处理传入的请求。

更多内容请参考:https://laravel-china.org/docs/psr/psr-7-http-message/1616

Intervention Image是一个开放源码的PHP图像处理和操作库。它提供了一种更简单、更有表现力的方法来创建、编辑和组合图像,并支持当前最常见的两个图像处理库GD库和Imagick。
具体使用方法可以参考:

  1. Laravel内使用:https://laravel-china.org/topics/1903/extension-recommended-interventionimage-image-processing
  2. 官方文档:http://image.intervention.io/getting_started/introduction
    下面主要说明一下PSR-7中的stream在这个库中怎么使用的。

    使用下面的代码可以生成一个
    PSR-7 stream as instance of GuzzleHttp\Psr7\Stream.

    // encode png image as jpg stream
    $stream = Image::make('public/foo.png')->stream('jpg', 60);
    

    然后有了$stream这个数据流对象,可以调用

    $code = $stream->getContents();
    file_put_contents('a.png',$code);
    

    这个getContents()方法就是Guzzle实现的PSR-7的Psr\Http\Message\StreamInterface接口

    Psr\Http\Message\StreamInterface
    

    实现源码

    public function getContents()
    {
     $contents = stream_get_contents($this->stream);
    
     if ($contents === false) {
         throw new \RuntimeException('Unable to read stream contents');
     }
    
     return $contents;
    }
    

    所以当我们安装Intervention Image的时候,就会首先安装GuzzleHttp\Psr7这个扩展包,下面是截图

    [03:36:47][vagrant@homestead:~/Code/Laravel] (master *)$  composer require intervention/image
    Using version ^2.4 for intervention/image
    ./composer.json has been updated
    Loading composer repositories with package information
    Updating dependencies (including require-dev)
    Package operations: 3 installs, 0 updates, 0 removals
    - Installing psr/http-message (1.0.1): Loading from cache
    - Installing guzzlehttp/psr7 (1.4.2): Loading from cache
    - Installing intervention/image (2.4.1): Loading from cache
    intervention/image suggests installing ext-imagick (to use Imagick based image processing.)
    intervention/image suggests installing intervention/imagecache (Caching extension for the Intervention Image library)
    Writing lock file
    Generating optimized autoload files
    > Illuminate\Foundation\ComposerScripts::postAutoloadDump
    > @php artisan package:discover
    Discovered Package: fideloper/proxy
    Discovered Package: laravel/tinker
    Discovered Package: intervention/image
    Package manifest generated successfully.
    

    可以看到在安装intervention/image的时候,也安装了

    - Installing psr/http-message (1.0.1): Loading from cache
    - Installing guzzlehttp/psr7 (1.4.2): Loading from cache
    
«上一篇: :下一篇»
  1. 还没有任何评论,你来说两句吧

Leave a reply