PHP 保存调整大小的图像

PHP save a resized image

我有这个 PHP 脚本可以调整图像大小并显示结果图像:

$filename = 'my-image.jpeg';

// Content type
header('Content-Type: image/jpeg');

// Get new dimensions
list($width, $height) = getimagesize($filename);
$new_width = 1200;
$new_height = ceil($height * ($new_width/$width));

// Resample
$image_p = imagecreatetruecolor($new_width, $new_height);
$image = imagecreatefromjpeg($filename);
imagecopyresampled($image_p, $image, 0, 0, 0, 0, $new_width, $new_height, $width, $height);

// Output
imagejpeg($image_p, null, 100);

现在我想保存图片而不是显示图片,保留原来的图片,并将新建的图片命名为"my-image-resized.jpeg",如何?

imagejpeg function reference所述,函数定义为:

bool imagejpeg ( resource $image [, mixed $to [, int $quality ]] )

第二个参数(如$to),说明如下:

The path or an open stream resource (which is automatically being closed after this function returns) to save the file to. If not set or NULL, the raw image stream will be outputted directly.

因为你把NULL传给了$to参数,所以是直接流,也就是显示。为了将它保存到文件系统,你应该这样做:

imagejpeg($image_p, 'sampleImage.jpg' , 100);