followloop / imaging
Laravel包,简化与模型关联的图像处理方式。
该包的官方仓库似乎已消失,因此该包已被冻结。
Requires
- php: >=5.5.9
- followloop/validation-service: 0.1.*
- illuminate/config: 5.*
- illuminate/console: 5.*
- illuminate/database: 5.*
- illuminate/filesystem: 5.*
- illuminate/http: 5.*
- illuminate/queue: 5.*
- intervention/image: ^2.3
This package is not auto-updated.
Last update: 2021-05-01 01:11:20 UTC
README
提供一种简洁方式处理与模型关联的图像的包。
目标
我们经常需要使用与模型关联的图像(如个人资料图片),实现这一过程总是相当固定:上传图像,存储它,调整大小,将缩略图和原始图像移动到云端存储等。有时事情会更复杂,我们必须调整现有图像的大小,删除旧图像等。
因此,该包的目标是提供一种整洁且干净的方式来处理与模型关联的这类图像,使我们能够以同步和异步的方式存储和处理它们(调整大小、删除旧图像等),从而减少我们需要在项目中集成此功能的工作量。
安装
- 通过将此包添加到您的
composer.json
或在项目文件夹中运行composer require followloop/imaging
来安装此包。 - 将提供者添加到您的
config/app.php
文件中:LOOP\Imaging\ImagingServiceProvider::class
- 通过运行
php artisan vendor:publish --provider="LOOP\Imaging\ImagingServiceProvider::class"
发布配置文件。 - 打开配置文件(
config/imaging.php
),并根据您的需求进行设置。继续阅读以了解参数的含义。 - 一切准备就绪!
使用
该包提供了5个不同的功能
- 图像模型:您可以使用此模型在实体中建立关系。
- 配置文件:它包含用于磁盘和图像驱动程序的设置。
- 图像服务:允许您上传、处理和删除图像。
- 事件/监听器:允许您处理图像操作(处理、将它们移动到CDN等)。
- 命令:允许您清除已删除的图像(从磁盘中销毁)和调整现有图像的大小。
图像模型
模型位于 LOOP\Imaging\Models\Image
。您应在所有可能包含图像的模型中将此模型包含为关系。此模型包含两个主要函数,它们仅返回一些值
+ thumbnails( $size = NULL, $onlyPath = FALSE): 调用此函数将返回为该图像生成的缩略图。默认情况下,该函数返回所有缩略图的完整URL。您也可以选择一个大小(第一个参数)或返回图像的路径(第二个参数)。
+ url(): 返回原始图像的完整URL。
配置文件
它包含使包正常工作的所需参数。
/*
|--------------------------------------------------------------------------
| Driver for image processing
|--------------------------------------------------------------------------
| The driver that you want to use to process the images.
|
| Accepted values: 'gd', 'imagick'
|
/
'driver' => 'gd',
/*
|--------------------------------------------------------------------------
| Local disk name
|--------------------------------------------------------------------------
|
| All images are first uploaded/stored in your local disk, so please
| specific the name of disk you want to use for this.
|
| You can add more disks in config/filesystems.php
|
*/
'local_disk_name' => 'local',
/*
|--------------------------------------------------------------------------
| Local disk URL
|--------------------------------------------------------------------------
|
| When the image is not moved to the cloud yet, it still needs to be
| served, so please specify here the full URL to the base folder
| where you store the uploaded images in your local disk.
*/
'local_disk_url' => 'http://temporal-url',
/*
|--------------------------------------------------------------------------
| Cloud disk URL
|--------------------------------------------------------------------------
|
| After one image is uploaded and processed, it can be moved to the cloud.
| To do so, besides wiring up the events and listeners, you have to
| specify a cloud disk here. If you do not want to use a cloud disk,
| just leave this empty.
|
| You can add more disks in config/filesystems.php
|
*/
'cloud_disk_name' => '',
/*
|--------------------------------------------------------------------------
| Cloud disk URL
|--------------------------------------------------------------------------
|
| Same as local disk URL, but for the cloud. This URL will be used
| once (and if) the images have been moved to the cloud.
|
*/
'cloud_disk_url' => '',
图像服务
图像服务绑定到位于 LOOP\Imaging\Services\ImageServiceInterface
的接口。该服务包含以下函数
/** * Finds an Image via the given ID, and returns an Image instance or an array with the errors. * * @param int $imageId ID of the image to find. * @return mixed Image instance if success, array otherwise. */ public function findImageById( $imageId ); /** * Creates a new Image in the system. * * @param mixed $imageB64OrUploadedFile Anything that can create an image on the Intervention's make() function. * @param array $options Array of options when creating the image. The options can be: * - path => Path where the image needs to be stored. * - sizes => Associative array of sizes that this image needs to be resized to. * - type => If the image belongs to a certain type, add it here. Useful to segregate. * @return mixed array or false in case of error, instance of the Image, in case of success. */ public function createImage( $imageB64OrUploadedFile, array $options = [] ); /** * Deletes (soft deletes) an image from the database * * @param int $imageId Id of the image to delete. * @param bool|true $skipValidation If this is set to true, the validation will be skipped and the function won't * check if the entity exists in the DB. * @return mixed true if success, array with error otherwise. */ public function deleteImage( $imageId, $skipValidation = TRUE); /** * Processes an image stored in the local disk, and resizes it to the given sizes. * * @param mixed $imageIdOrImage ID of the image, or instance of the image to process. * @param array $sizes associative array with the sizes that the image needs to be resized to. * @return mixed Image instance. */ public function processImage( $imageIdOrImage, array $sizes = [] ); /** * Destroy an image (and its thumbs) from the disks and from the DB. It cannot be reverted. * * @param mixed $imageIdOrImage ID or instance of the image to destroy. * @return mixed true if success, array with errors otherwise. */ public function destroyImage( $imageIdOrImage );
事件/监听器
包含一些事件和监听器
事件
LOOP\Imaging\Events\ImageWasCreated: 当新图像成功上传并创建在数据库/本地磁盘时触发。
LOOP\Imaging\Events\ImageWasProcessed: 当图像被处理并生成缩略图(本地)时触发。
LOOP\Imaging\Events\ImageWasMovedToCloud: 当图像(及其所有缩略图)移动到云盘时触发。
LOOP\Imaging\Events\ImageWasDeleted: 当图像被删除(软删除)时触发。
===========
监听器
LOOP\Imaging\Listeners\ProcessImageAsync: 异步(排队)处理接收到的图像。它可以订阅 ImageWasCreated 事件。
LOOP\Imaging\Listeners\ProcessImageSync: 同步(不排队)处理接收到的图像。它可以订阅 ImageWasCreated 事件。
LOOP\Imaging\Listeners\MoveProcessedImagesToCloudImageAsync: 异步(排队)将处理后的图像及其缩略图移动到云盘。它可以订阅 ImageWasProcessed 事件。
LOOP\Imaging\Listeners\MoveProcessedImagesToCloudImageSync: 同步(不排队)将处理后的图像及其缩略图移动到云盘。它可以订阅 ImageWasProcessed 事件。
LOOP\Imaging\Listeners\RemoveLocalImageAsync: 异步(排队)删除接收到的图像的本地文件。它可以订阅 ImageWasMovedToCloud 事件。
LOOP\Imaging\Listeners\RemoveLocalImageSync: 同步(不排队)删除接收到的图像的本地文件。它可以订阅 ImageWasMovedToCloud 事件。
要配置它们,只需将它们添加到位于 app/Providers/EventServiceProvider.php
的 EventServiceProvider 中。
如您所见,存在异步和同步事件。根据您的需求仅订阅其中一个。
命令
包含2个命令,帮助您维护图像。
php artisan imaging:purge-deleted-images {--days=30}:
删除所有被删除(默认为30天或更久)的图像,并从数据库以及本地和远程磁盘中销毁它们。
php artisan imaging:resize {--image-id=} {--image-type=} {--sizes=}
将指定的图像(通过 -image-id
)或一组指定的图像(通过 --image-type
)调整到通过 --sizes
提供的新尺寸。
注意:--sizes
应包含所有尺寸,而不仅仅是新尺寸。所有其他不在此参数中存在的图像版本将被删除。此参数应具有以下结构:“big:500x500,small:100x100,medium:x250”。
实际示例
假设您有一个用户实体,其中包含个人资料图片。您应该像这样包含与 Image 实体的关系
public function profile_picture() { return $this->hasOne( \LOOP\Imaging\Models\Image::class, 'id', 'profile_picture_id' ); }
每次您需要更新图像时,都需要使用提供的 Image 服务。我们建议您一次处理图像创建和旧图像删除,以便保持图像更新和同步。以下是一个函数示例
protected function createAndSaveProfilePictureForUser( $image, User $user ) { if ( $image ) { $prefix = substr( $user->id , 0, 3); $options = [ 'sizes' => [ 'large' => '600x600', 'medium' => '300x300', 'small' => '100x100' ], 'path' => sprintf( 'users/%s/%s/%s/', $prefix, $user->id, (string)date('dmY') ), 'crop' => TRUE ]; $imageResult = $this->imageService->createImage( $image , $options ); if ( $imageResult instanceof Image ) { $saveData = [ 'picture_id' => $imageResult->id ]; // Remove other image from post. $userPictureId = $user->picture_id; if ( $userPictureId ) $this->imageService->deleteImage( $userPictureId, TRUE ); $this->usersRepository->updateBy( $saveData, $user->id ); $user = $this->usersRepository->findOneBy( $user->id ); return $user; } return $imageResult; } return $user; }
$image
可以是任何可以创建 Intervention Image 对象实例的东西。
然后,每次您调用函数来创建或更新用户时,都可以包含此方法来更新图片
public function updateUser( User $user, array $newUserData ) { ... ... if ( array_key_exists( 'profile_picture', $newUserData ) ) { $user = $this->createAndSaveProfilePictureForUser( $newUserData['profile_picture'], $user ); unset( $newUserData['profile_picture'] ); } ... ... return $user; }
为了使所有这些操作自动完成,您的EventServiceProvider应该连接事件和监听器
protected $listen = [ 'LOOP\Imaging\Events\ImageWasCreated' => [ 'LOOP\Imaging\Listeners\ProcessImageSync' ], 'LOOP\Imaging\Events\ImageWasProcessed' => [ 'LOOP\Imaging\Listeners\MoveProcessedImagesToCloudImageSync' ], 'LOOP\Imaging\Events\ImageWasMovedToCloud' => [ 'LOOP\Imaging\Listeners\RemoveLocalImageSync' ] ];
这样,我们将所有事件连接到监听器,以便
- 一旦图片创建完成(E)--> 异步处理图片(L)。
- 一旦处理完成(E)--> 异步将其移动到云端(L)。
- 一旦移动到云端(E)--> 从本地磁盘删除它(L)。
当然,您可以设置这些监听器自动处理(通过在监听器名称中将'Async'替换为'Sync')。
这就完成了!
变更日志
-- 尚未发布版本 - 不建议在生产中使用 --
鸣谢
错误 & 贡献
- 发现了错误?这既是好事也是坏事。请通过Github上的问题来告知我。
- 需要功能或有一些有趣的内容要贡献?太好了!发起一个pull请求。
许可证
??