PHP可以通过图片处理库GD库(Graphics Draw)来控制图片大小。GD库提供了一系列图片处理函数,包括缩放、裁剪、旋转、水印等功能。
下面是一个简单的例子,用PHP GD库控制图片大小:
// 打开原始图像
$source_img = imagecreatefromjpeg("original.jpg");
// 获取原始图像的宽度和高度
$source_width = imagesx($source_img);
$source_height = imagesy($source_img);
// 设置缩放后的图像大小
$thumb_width = 200;
$thumb_height = 150;
// 创建一个空白的缩略图像
$thumb_img = imagecreatetruecolor($thumb_width, $thumb_height);
// 将原始图像缩放到缩略图像
imagecopyresampled(
$thumb_img,
$source_img,
0, 0, 0, 0,
$thumb_width, $thumb_height,
$source_width, $source_height
);
// 输出缩略图像
header("Content-Type: image/jpeg");
imagejpeg($thumb_img);
// 释放缩略图像和原始图像的内存
imagedestroy($thumb_img);
imagedestroy($source_img);
在上面的例子中,首先使用imagecreatefromjpeg
函数打开原始图像,并使用imagesx
和imagesy
函数获取原始图像的宽度和高度。然后设置缩略图像的大小,并使用imagecreatetruecolor
函数创建一个空白的缩略图像。接着使用imagecopyresampled
函数将原始图像缩放到缩略图像。最后使用header
函数设置输出为JPEG格式,使用imagejpeg
函数输出缩略图像,并使用imagedestroy
函数释放缩略图像和原始图像的内存。