在PHP中,我们可以使用GD库来处理图像,以下是一个简单的PHP图片缩放类示例:

(图片来源网络,侵删)
class ImageResizer {
private $image;
private $width;
private $height;
private $type;
public function __construct($file) {
list($this->width, $this->height, $this->type) = getimagesize($file);
switch ($this->type) {
case IMAGETYPE_JPEG:
$this->image = imagecreatefromjpeg($file);
break;
case IMAGETYPE_PNG:
$this->image = imagecreatefrompng($file);
break;
case IMAGETYPE_GIF:
$this->image = imagecreatefromgif($file);
break;
default:
throw new Exception('Unsupported image type.');
}
}
public function resize($newWidth, $newHeight) {
$newImage = imagecreatetruecolor($newWidth, $newHeight);
imagecopyresampled($newImage, $this->image, 0, 0, 0, 0, $newWidth, $newHeight, $this->width, $this->height);
$this->image = $newImage;
$this->width = $newWidth;
$this->height = $newHeight;
}
public function save($outputFile, $quality = 100) {
switch ($this->type) {
case IMAGETYPE_JPEG:
imagejpeg($this->image, $outputFile, $quality);
break;
case IMAGETYPE_PNG:
imagepng($this->image, $outputFile, round(9 * $quality / 100));
break;
case IMAGETYPE_GIF:
imagegif($this->image, $outputFile);
break;
}
}
} 使用方法
1、创建一个ImageResizer对象,传入要缩放的图片文件路径。
2、调用resize方法,传入新的宽度和高度。
3、调用save方法,传入输出文件路径和可选的质量参数(仅对JPEG和PNG有效)。
示例代码

(图片来源网络,侵删)
try {
$resizer = new ImageResizer('input.jpg');
$resizer->resize(300, 200);
$resizer->save('output.jpg', 80);
} catch (Exception $e) {
echo 'Error: ' . $e->getMessage();
} 这个示例将input.jpg图片缩放到300x200像素,并将结果保存为output.jpg,质量设置为80%。
各位小伙伴们,我刚刚为大家分享了有关php图片缩放类_PHP的知识,希望对你们有所帮助。如果您还有其他相关问题需要解决,欢迎随时提出哦!

(图片来源网络,侵删)
本文来源于互联网,如若侵权,请联系管理员删除,本文链接:https://www.9969.net/75228.html