laravel 的 intervention-image 图像处理

前文为PHP安装imagick,现在在laravel 5.5中使用intervention-image 

安装:
	需求:
		PHP >= 5.4
		Fileinfo 扩展
		GD库 >= 2.0
		Imagick 扩展 >=6.5.7
	composer安装:
		composer require intervention/image
	laravel配置:
		1.编辑 config/app.php
			$providers 添加 'Intervention\Image\ImageServiceProvider::class'
			$aliases 添加 ''Image' => Intervention\Image\Facades\Image::class'
		2.默认使用的是 'GD' 库,想修改的话,需要配置驱动,我们来生成配置文件:
			php artisan vendor:publish --provider="Intervention\Image\ImageServiceProviderLaravel5"
			生成 config/image.php 配置文件
		3.PHP涉及到的配置项:
			memory_limit - 最大内存限制
			upload_max_filesize - 如果上传图片时,可能修改
			-----
			其实,可能还有好多
			max_execution_time - 最大执行时间
			...

1. 安装#

1). 使用 composer 安装:

composer require intervention/image

上面的命令在Laravel 5.5中,会自动安装并注册providers和aliases

2). 如果是laravel 5.5以下版本。需修改 app/config/app.php 添加 ServiceProvider:

// 将下面代码添加到 providers 数组中
'providers' => [
    // ...
    Intervention\Image\ImageServiceProvider::class,
    // ...
  ],

// 将下面代码添加到 aliases 数组中
'aliases' => [
    // ...
    'Image' => Intervention\Image\Facades\Image::class,
    // ...
  ],

2. 图片处理库的配置#

此扩展包默认使用 PHP 的 GD 库来进行图像处理, 但由于 GD 库对图像的处理效率要稍逊色于 imagemagick 库, 因此这里推荐替换为 imagemagick 库来进行图像处理.

GD在php7是自带的,安装Imagick前文有介绍.

在使用 Intervention Image 的时候, 你只需要给 ImageManager 传一个数组参数就可以完成 GD 和 Imagick 库之间的互相切换.

如下所示:

// 引入 composer autoload
require 'vendor/autoload.php';

// 导入 Intervention Image Manager Class
use Intervention\Image\ImageManager;

// 通过指定 driver 来创建一个 image manager 实例
$manager = new ImageManager(array('driver' => 'imagick'));

// 最后创建 image 实例
$image = $manager->make('public/foo.jpg')->resize(300, 200);

另外你也可以使用 ImageManager 的静态版本, 如下所示:

// 引入 composer autoload
require 'vendor/autoload.php';

// 导入 Intervention Image Manager Class
use Intervention\Image\ImageManagerStatic as Image;

// 通过指定 driver 来创建一个 image manager 实例 (默认使用 gd)
Image::configure(array('driver' => 'imagick'));

// 最后创建 image 实例
$image = Image::make('public/foo.jpg')->resize(300, 200);

以上配置可以在Controller中添加,也可使用默认。如果更改driver,可在image.php更改

生成 config/image.php 配置文件:

php artisan vendor:publish --provider="Intervention\Image\ImageServiceProviderLaravel5"

运行上面的命令后, 会在项目中生成 config/image.php 配置文件, 打开此文件并将 driver 修改成 imagick:

return array(
    'driver' => 'imagick'
);

到此, 此拓展包即安装成功 

3. 基础用法#

// 修改指定图片的大小
$img = Image::make('images/avatar.jpg')->resize(200, 200);

// 插入水印, 水印位置在原图片的右下角, 距离下边距 10 像素, 距离右边距 15 像素
$img->insert('images/watermark.png', 'bottom-right', 15, 10);

// 将处理后的图片重新保存到其他路径
$img->save('images/new_avatar.jpg');

/* 上面的逻辑可以通过链式表达式搞定 */
$img = Image::make('images/avatar.jpg')->resize(200, 200)->insert('images/new_avatar.jpg', 'bottom-right', 15, 10);

4. 特色功能#

除上文介绍的基本用法之外, 此扩展包还支持:

  • 图片上传功能;
  • 图片缓存功能;
  • 图片过滤功能: 将图片按照统一规则进行转换;
  • 图片动态处理: 根据访问图片的 URL 参数自动调整图片大小


图片上传:
	1.直接从 $_FILES 中,获取 'tmp' 临时图片数据
		$img = Image::make($_FILES['image']['tmp_name']);		// Image::make() 支持这种方式
		$img->fit(300, 200);
		$img->save('public/bar.jpg');
	2.在laravel中处理图片上传
		Image::make(Input::file('photo'));						// Input::file() 来获取$_FILES

图片过滤器:
	图片过滤器,给了我们非常有用的方式,将多个图像转换命令集合在一个专用类中。(可将多个图像处理步骤,封装成一个过滤器)。
	Intervention/image,提供了基本接口(Intervention\Image\Filters\FilterInterface),所有的过滤器都需要实现它。
	调用过滤器:
		$img = Image::make('foo.jpg');
		$img->filter(new DemoFilter(5));
	定义过滤器:
		src/Intervention/Image/Filters/DemoFilter.php
		<?php
			namespace Intervention\Image\Filters;

			class DemoFilter implements FilterInterface
			{
			    /**
			     * Default size of filter effects
			     */
			    const DEFAULT_SIZE = 10;

			    /**
			     * Size of filter effects
			     *
			     * @var integer
			     */
			    private $size;

			    /**
			     * Creates new instance of filter
			     *
			     * @param integer $size
			     */
			    public function __construct($size = null)
			    {
			        $this->size = is_numeric($size) ? intval($size) : self::DEFAULT_SIZE;
			    }

			    /**
			     * Applies filter effects to given image
			     *
			     * @param  Intervention\Image\Image $image
			     * @return Intervention\Image\Image
			     */
			    public function applyFilter(\Intervention\Image\Image $image)
			    {
			        $image->pixelate($this->size);
			        $image->greyscale();

			        return $image;
			    }
			}
		?>

图像缓存:
	图像缓存包,扩展了缓存图像的能力。

	缓存包使用laravel的 'Illuminate/Cache' 包。基于laravel的缓存配置,可以使用 '文件系统'、'数据库'、'Memcached'或'Redis' 来作为临时缓冲存储

	原理很简单。一旦安装了缓存包,就可以调用静态缓存方法。每个对 Intervention/Image 类的方法调用,都会被缓存接口捕获和检查。如果这个特定的操作序列意境生成过,将直接从缓存中获取数据,而不是重新执行一遍资源密集型的GD操作

	安装:
		composer require intervention/imagecache

	使用方式:
		$img = Image::cache(function($image){
			$image->make('public/foo.jpg')->resize(300, 200)->greyscale();
		});

基于URL的图像操作:
	在Laravel应用程序中,可以使用URL来动态操作图像。 URL图像的操作版本将存储在缓存中,并且将直接加载而无需资源密集型GD操作。

	图像必须上传一次。当通过HTTP请求方式访问文件,所有操作(例如:调整大小、裁剪)将稍后处理,例如:
		http://yourhost.com/{route-name}/{template-name}/{file-name}

	1.安装:
		composer require intervention/image
		composer require intervention/imagecache
	2.生成配置文件
		php artisan vendor:publish
		生成 config/imagecache.php
	3.启用操作
		默认情况下,基于URL的图像操作是关闭的。在imagecache.php配置文件中,来指定 'route' 配置项
			'route' => 'imagecache'	
		配置好route后,可以通过artisan命令,列出所有已注册的路有,并检查新路有是否正确列出:
		  	php artisan route:list
	4.定义资源目录
		告诉PHP,在哪里搜索图片。我们可以定义自己喜欢的任意数量的目录。例如:定义应用程序的所有上传目录。应用程序将在目录中搜索在路有中提交的文件。
			'paths' => array(
				'storage/uploads/images',
				public_path('img'),
			),
		在这些目录中保存具有唯一文件名的图像文件是有意义的。否则,包将返回首先找到的图像。
		注意:	
			出于安全原因,路由仅接受由以下字符组成的文件名:
				a-zA-Z0-9-_/.
	5.模板
		模板的定义,就是过滤器类的名称,可以在其中定义任意操作命令(之前介绍过过滤器)。系统自带3个基本模板:
			small - 120x90 
			medium - 240x180
			large - 480x360
		我们可以在配置文件中,自由配置可用的模板:
			'templates' => array(
				'small' => 'Intervention\Image\Templates\Small',
				'medium' => 'Intervention\Image\Templates\Medium',
				'large' => 'Intervention\Image\Templates\Large',
			),
		访问原始图片:
			original - 使用原始图像文件,发送HTTP响应
			download - 发送HTTP响应并强制浏览器下载原始图像文件,而不是显示它。
			例如:
				http://yourhost.com/{route-name}/original/{file-name}
	6.图像缓存的生命周期:
		一旦第一次访问了URL,搜索图片,并根据模板,编辑图像,并存储到缓存中。 所以下次访问URL时,所有的GD操作都被绕过,文件将直接来自缓存
			'lifetime' => 43200,		// 单位是 'minutes-分钟'


支持的格式:
	图片格式:
		GD库:jpeg, png, gif
		Imagick库:jpeg, png, gif, tif, bmp, ico, psd
	颜色格式:
		整数
			$color = Image::make('public/foo.jpg')->pickColor(10, 10);	// pickColor()返回的是整数形式的RGB值
			$img->fill($color);
		数组
			$img->fill(array(255, 0, 0));
			$img->fill(array(255, 0, 0, 0.5));
		16进制
			$img->fill('#000000');
		RGB和RGBA字符串格式
			$img->fill('rgb(255, 0, 0)');
			$img->fill('rgb(255, 0, 0, 0.5)');

创建图像:
	1.canvas($width, $height [, mixed $bgcolor]) - 创建一个空的画布

		构造方法,使用给定的宽、高,创建一个新的空的图像实例。可以选择性的定义一个背景色。默认画布背景是透明(transparent)的。

		示例:
			$img = Image::canvas(800, 600);
			$img = Image::canvas(32, 32, '#ff0000');

	2.make($source) - 从给定的资料中读取图像

		从资源中创建新的图像实例的通用工厂方法。该方法高度可变,可读取下面列出的所有输入类型:
			string - 文件系统的图片路径
			string - 图片的URL地址(allow_url_fopen必须启用)
			string - 二进制图片数据
			string - data-url编码的图片数据
			string - base64编码的图片数据
			resource - gd类型的PHP资源(当使用GD库)
			object - Imagick实例(当使用Imagick库)
			object - Intervention\Image\Image 实例
			object - SplFileInfo instance (To handle Laravel file uploads via Symfony\Component\HttpFoundation\File\UploadedFile) - laravel框架自带的图片上传实例

销毁图像:
	1.destroy() - 销毁图像

		在PHP脚本结束前,释放当前图像实例相关的内存。通常资源会在脚本结束后,自动释放。
		当然,该方法调用后,图像实例不再可用。

		示例:
			$img = Image::make('public/foo.jpg');
			$img->resize(320, 240);
			$img->save('public/small.jpg');
			$img->destroy();

图像输出:
	1.response([string $format [, integer $quality]]) - 直接作为HTTP响应

		以指定的格式和图像质量,来发送当前图像,作为HTTP响应
		$format - 可以是:jpg,png,gif,tif,bmp。默认是jpeg
		$quality - 从0-100.默认是90

	2.save([string $path [, int $quality]]) - 保存图像到指定路径(未指定,则表示覆盖原图)

		将图像对象的当前状态保存到文件系统中。可指定路径和图像质量。
		保存到图像类型通过文件后缀来定义。例如:foo.jpg 图片将被保存为 'JPG' 格式。如果未指定可用后缀,首先尝试图像的MIME类型,如果失败,将被编码为 'JPEG'
		此外,图像将始终以RGB颜色模式保存,而没有嵌入的颜色配置文件。
		$path - 指定图像数据写入的文件路径。如果图像是从一个存在的文件路径创建的,同时我们未指定 $path,将会尝试覆盖该路径。

		示例:
			$img = Image::make('public/foo.jpg')->resize(300, 200);
			$img->save('public/bar.png', 60);
			$img->save('public/bar.jpg');

	3.stream([mixed $format [, int $quality]]) - 图像流

		以给定格式和给定图像质量,对当前图像进行编码,并基于图像数据,创建新的PSR-7流。

	4.encode([$format [, $quality]]) - 图像进行编码

		将当前图片,按给定的格式和图片质量进行编码

		$format - jpg、png、gif、tif、bmp、data-url(base64)。默认返回的编码后的数据。默认类型是 'jpeg'
		$quality - 返回从 0-100。0-最低,100最大。只对 'jpg' 编码格式有效,因为png压缩是无损的,不会影响图片质量。默认是90

		示例:
			$jpg = (string) Image::make('public/foo.png')->encode('jpg', 75);
			$data = (string) Image::make('public/foo.png')->encode('data-url');

图像缓存相关
	1.cache(Closure $callback [, int $lifetime [,bool $returnObj]]) - 图像缓存

		$callback - 从Closure回调,创建新的缓存图像实例。
		$lifetime - 为回调传递一个生命周期
		$returnObj - 获取一个Intervention图像实例作为返回值,还是直接接收图像流。
		cache()方法,需要安装额外的 'intervention/imagecache' 依赖包

		示例:
			$img = Image::cache(function($image){
				$image->make('public/foo.jpg')->resize(300, 200)->greyscale();
			}, 10, true);

	2.backup($name = 'default') - 图像状态备份

		备份当前图片的状态。将图片的当前状态备份到 $name。之后,可以调用 reset($name = 'default') 来进行状态恢复。

		$name默认是'default'。我们可以传递不同的$name,来记录图片处理过程中的多个状态

		示例:
			$img = Image::canvas(120, 90, '#000');
			$img->fill('#f00');
			$img->backup();
			$img->fill('#0f0');
			$img->reset();

	3.reset($name = 'default') - 图像状态恢复

		backup()用于备份图像状态,reset()用于恢复到之前的某个备份	

原生图像处理驱动调用:
	1.getCore() - GD库|Imagick库 对象调用

		以特定驱动的核心格式,返回当前图像。如果使用的是 'GD' 库,则返回 GD 资源类型;如果使用的是 'Imagick',则返回一个 Imagick 对象。

		示例:
			$img = Image::make('public/foo.jpg');
			$imagick = $img->getCore();			// 返回原始的 'imagick' 对象
			$imagick->embossImage(0, 1);		// 就可以调用 'imagick' 的方法了

调整图像尺寸:
	1.resize($width, $height [,Closure $callback]) - 调整图像尺寸

		使用给定的宽、高,来调整当前图像。传递一个可选的Closure回调来约束resize命令。
		回调函数,定义了resize命令的约束。可约束图像的 '宽高比(aspect-ratio)' 和 '不希望的大小(a unwanted upsizing)'
			aspectRatio()
				约束当前图像的宽高比。作为比例调整大小的快捷方式,可以使用 widen() 和 heighten()
			upsize()
				保持图像大小

		示例:
			$img = Image::make('public/foo.jpg');
			$img->resize(300, 200);
			$img->resize(300, null);
			$img->resize(null, 200);
			$img->resize(300, null, function($constraint){		// 调整图像的宽到300,并约束宽高比(高自动)
				$constraint->aspectRatio();
			});
			$img->resize(null, 200, function($constraint){		// 调整图像的高到200,并约束宽高比(宽自动)
				$constraint->aspectRatio();
			});
			$img->resize(null, 400, function($constraint){		// 阻止可能的尺寸变化(保持图像大小)
				$constraint->aspectRatio();
				$constraint->upsize();
			});

	2.widen($width [, Closure $callback]) - 调整图像宽(保持宽高比)

		调整图像的宽到给定的宽度,保持宽高比。传递一个可选的回调函数,来应用额外的约束,例如:阻止可能的尺寸变化
			upsize()
				保持图像大小

	3.heighten($height [, Closure $callback]) - 调整图像高(保持宽高比)

		调整图像的高到给定的高度,保持宽高比。传递一个可选的回调函数,来应用额外的约束,例如:阻止可能的尺寸变化
			upsize()
				保持图像大小

	4.crop($width, $height [, $x, $y]) - 裁剪图像

		使用给定的宽、高,裁剪当前图像的一个矩形区域。默认从图像的0.0开始,可传递一个坐标,定位裁剪的起始点。

		示例:	
			$img = Image::make('public/foo.jpg');
			$img->crop(100, 100, 20, 20);

	5.fit($width [[$height] [, Closure $callback [, $position]]]) - 智能裁剪和调整

		以一个智能的方式,结合裁剪和调整来格式化图片。该方法将会自动找到给定的宽、高的最佳宽高比,裁剪并调整到给定尺寸。
		$callback - 回调函数,来约束可能的尺寸变化
			upsize()
				保持图像大小

		$position - 自定义裁剪的位置。默认是 '中心'
			top-left
			top
			top-right
			left
			center(默认)
			right
			bottom-left
			bottom
			bottom-right

	6.resizeCanvas($width, $height [, $anchor [, bool $relative [, $bgcolor]]])

		调整当前图像的边界到给定的宽和高。

		$anchor - 从图像的哪点开始调整
			top-left
			top
			top-right
			left
			center(默认)
			right
			bottom-left
			bottom
			bottom-right

		$relative - 将模式设置为相对,用以在真实的图片尺寸上,添加或者减去给定的宽、高。

		$bgcolor - 画布背景(默认 '#000000')

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值