sayme/simple-image-cropper

此包已被弃用且不再维护。未建议替代包。

一个轻量级的PHP库,用于裁剪和调整图像大小。

dev-master 2018-03-11 19:53 UTC

This package is auto-updated.

Last update: 2023-03-23 16:32:30 UTC


README

一个轻量级的PHP库,用于裁剪和调整图像大小。

Build Status

使用方法

下载并安装 SimpleImageCropper

要安装 SimpleImageCropper,请运行以下命令

$ composer require sayme/simple-image-cropper

初始化

使用URL作为图像源初始化 SimpleImageCropper。

use SimpleImageCropper\Cropper;

$cropper = new Cropper('http://example.com/your-image.png');

或者,您可以使用 $_FILES['filename']['tmp_name'] 作为源。

$cropper = new Cropper($_FILE['filename']['tmp_name']);

初始化裁剪器时,您将可以访问一些原始图像元数据。

  • 图像宽度 $cropper->getWidth()
  • 图像高度 $cropper->getHeight()
  • 图像类型 $cropper->getType()

裁剪并保存图像

在中心裁剪图像并保存新图像。

$width = 150;
$height = 150;
// This will crop the image in center with the new width and height
$cropper->crop($width, $height);

// This will save your new image as mynewimage.png in the current directory
$cropper->save('mynewimage.png');

// You can also set the quality of the image to be saved in the second parameter.
// The quality is by default 75, you can set it to a quality between 0-100
$cropper->save('mynewumage.png', 50);

以BLOB形式输出图像

您还可以将图像以BLOB形式输出以保存到数据库或直接输出。

echo $cropper->getData();

设置png的背景颜色

您还可以设置png的背景颜色(RGB)

// set the color
$color = [
    'r' => 150,
    'g' => 150,
    'b' => 150
];

$cropper->crop($width, $height, $color['r'], $color['g'], $color['b']);

示例

保存图像

use SimpleImageCropper\Cropper;

$cropper = new Cropper('http://example.com/your-image.png');

// Crop the image by 200x200
$cropper->crop(200, 200);

// Save the image as mynewimage.png
$cropper->save('mynewimage.png');

输出图像(BLOB)

// Set header
header('Content-Type: image/png');

use SimpleImageCropper\Cropper;

$cropper = new Cropper('http://example.com/your-image.png');

// Crop the image by 200x200 and output it.
echo $cropper->crop(200, 200)->getData();

调整图像大小并保持比例

$cropper = new Cropper($_FILES['filename']['tmp_name']);

// Set the new width
$newWidth = 306;

// Check proportions
$proportion = $newWidth / $img->width;

// Set the new height
$newHeight = $img->height * $proportion;

// Crop the image by its new width and height
$cropper->crop($newWidth, $newHeight);

// Save the image with a 50% quality
$cropper->save('mynewimage.png', 50);