使用PHP调整大小后保存图片

3

我正在改进我的Facebook应用程序。我需要能够调整图像大小,然后将其保存到服务器上的目录中。这是我用来调整大小的代码:

<?php
// The file
$filename = 'test.jpg';
$percent = 0.5;

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

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

// 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);
?>

我的问题是,我该如何保存这张调整过大小的图片?我需要吗?有没有一种方法可以在不保存它的情况下操作这张调整过大小的图片?


1
我不理解那个最后的句子? - Pekka
3个回答

8
根据imagejpeg()手册,可选的第二个参数可以指定文件名,它将被写入其中。

文件名

要保存文件的路径。如果未设置或为NULL,则原始图像流将直接输出。

要跳过此参数以提供质量参数,请使用NULL。

通常最好将结果写入磁盘进行基本缓存,以使不是每个传入请求都会导致(资源密集型)GD调用。

好的,完美。唯一我不喜欢的是它会显示出来。我决定最好在后台调整图像大小。有没有办法强制它只保存调整过大小的图像,而不是显示输出? - Zac Brown
@Zachary 我不明白。$image_p 已经是调整大小后的图像了,不是吗? - Pekka
是的,但我不想显示调整大小后的图像,只想保存。这可行吗? - Zac Brown
@Zachary 是的,就像上面所说,通过指定文件名来实现。还有什么遗漏的吗? - Pekka

3
function resize($img){
/*
only if you script on another folder get the file name
$r =explode("/",$img);
$name=end($r);
*/
//new folder
$vdir_upload = "where u want to move";
list($width_orig, $height_orig) = getimagesize($img);
//ne size
$dst_width = 110;
$dst_height = ($dst_width/$width_orig)*$height_orig;
$im = imagecreatetruecolor($dst_width,$dst_height);
$image = imagecreatefromjpeg($img);
imagecopyresampled($im, $image, 0, 0, 0, 0, $dst_width, $dst_height, $width_orig, $height_orig);
//modive the name as u need
imagejpeg($im,$vdir_upload . "small_" . $name);
//save memory
imagedestroy($im);
}

它应该正常工作



网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接