引言
准备工作
1. 获取图片信息
<?php
$image = imagecreatefromjpeg('path/to/image.jpg');
$width = imagesx($image);
$height = imagesy($image);
?>
2. 设置目标尺寸
根据你的需求,设置你想要的目标尺寸。这里以宽度为300像素为例。
<?php
$target_width = 300;
$target_height = ($height * $target_width) / $width;
?>
3. 创建新图片
使用imagecreatetruecolor()函数创建一个新的画布。
<?php
$new_image = imagecreatetruecolor($target_width, $target_height);
?>
4. 复制图片
<?php
imagecopyresampled($new_image, $image, 0, 0, 0, 0, $target_width, $target_height, $width, $height);
?>
5. 输出图片
<?php
header('Content-Type: image/jpeg');
imagejpeg($new_image, 'path/to/output.jpg');
?>
6. 清理资源
<?php
imagedestroy($image);
imagedestroy($new_image);
?>
7. 示例代码
<?php
$image = imagecreatefromjpeg('path/to/image.jpg');
$width = imagesx($image);
$height = imagesy($image);
$target_width = 300;
$target_height = ($height * $target_width) / $width;
$new_image = imagecreatetruecolor($target_width, $target_height);
imagecopyresampled($new_image, $image, 0, 0, 0, 0, $target_width, $target_height, $width, $height);
header('Content-Type: image/jpeg');
imagejpeg($new_image, 'path/to/output.jpg');
imagedestroy($image);
imagedestroy($new_image);
?>