nexwap/upstream

一个简单的Laravel 8 composer包,用于辅助文件上传和图片缩放/裁剪。

v0.6.10 2018-06-25 17:24 UTC

README

一个简单的Laravel 5 composer包,用于辅助文件上传和图片缩放/裁剪。

安装

要安装Upstream,请确保 regulus/upstream 已添加到Laravel 5的 composer.json 文件中。

"require": {
	"regulus/upstream": "0.6.*"
},

然后从命令行运行 php composer.phar update。Composer将安装Upstream包。现在,您只需注册服务提供者并在 config/app.php 中设置Upstream的别名即可。将以下内容添加到 providers 数组

Regulus\Upstream\UpstreamServiceProvider::class,

并将以下内容添加到 aliases 数组

'Upstream' => Regulus\Upstream\Facade::class,

最后,运行 php artisan vendor:publish 以发布配置文件和语言文件。

上传文件

$config = [
	'path'            => 'uploads/pdfs', // the path to upload to
	'field'           => 'file',         // name of field (use "fields" for an array with multiple fields)
	'filename'        => 'temp',         // the basename of the file (extension will be added automatically)
	'fileTypes'       => ['png', 'jpg'], // the file types to allow
	'createDirectory' => true,           // automatically creates directory if it doesn't exist
	'overwrite'       => true,           // whether or not to overwrite existing file of the same name
	'maxFileSize'     => '5MB',          // the maximum filesize of file to be uploaded
];

$upstream = Upstream::make($config);
$result   = $upstream->upload();

注意:特别提供的 filename 字符串包括 [LOWERCASE][UNDERSCORED][LOWERCASE-UNDERSCORED][DASHED][LOWERCASE-DASHED][RANDOM]。前五个用于对原始文件名进行格式调整。后者可用于将文件名设置为随机字符串(连同其原始扩展名)。

缩放图片和创建缩略图

$config = [
	'path'               => 'uploads/images',
	'fields'             => ['picture', 'picture2'],
	'filename'           => 'temp',
	'fileTypes'          => 'images',
	'createDirectory'    => true,
	'overwrite'          => true,
	'maxFileSize'        => '5MB',
	'imageResize'        => true,
	'imageResizeQuality' => 60,
	'imageCrop'          => true,
	'imageDimensions'    => [
		'w'  => 720, // image width
		'h'  => 360, // image height
		'tw' => 180, // thumbnail image width
		'th' => 180, // thumbnail image height
	],
];

$upstream = Upstream::make($config);
$result   = $upstream->upload();

src/config/config.php 配置文件中提供了一个完整的配置数组。您可以使用以下方法在上传图片后裁剪图片

$config = [
	'path'            => 'uploads/images',
	'filename'        => 'temp-'.$id.'.jpg',
	'newFilename'     => $id.'.jpg',
	'createDirectory' => true,
	'overwrite'       => true,
	'imageThumb'      => true,
	'imageDimensions' => [
		'w'  => 260, // image width
		'h'  => 260, // image height
		'tw' => 120, // thumbnail image width
		'th' => 120, // thumbnail image height
	],
	'cropPosition' => [
		'x' => $input['x'],      // X position
		'y' => $input['y'],      // Y position
		'w' => $input['width'],  // width of cropped area
		'h' => $input['height'], // height of cropped area
	],
];

$result = Upstream::cropImage($config);

您可以使用JavaScript图片裁剪器,如Cropper来设置cropPosition。如果您将cropPosition设为null或不设置,则图片将首先缩放到目标尺寸的140%,然后从中心裁剪。