1. 选择合适的库

2. 安装 GD 库

如果你的 PHP 环境中没有安装 GD 库,可以通过以下命令进行安装:

sudo apt-get install php-gd

对于 Windows 系统,可以通过 PHP 安装程序进行安装。

3. 读取图片

<?php
$image = imagecreatefromjpeg('example.jpg');
?>

4. 获取图片尺寸

<?php
$width = imagesx($image);
$height = imagesy($image);
?>

5. 设置新的图片大小

<?php
$new_width = 200;
$new_height = 200;

$thumbnail = imagecreatetruecolor($new_width, $new_height);
imagecopyresampled($thumbnail, $image, 0, 0, 0, 0, $new_width, $new_height, $width, $height);
?>

6. 输出图片

<?php
imagejpeg($thumbnail, 'example_small.jpg');
?>

7. 清理

<?php
imagedestroy($image);
imagedestroy($thumbnail);
?>

总结