PHP 图片调整大小无效

PHP image resize not working

我正在尝试从 JPG 图片创建缩略图,但无法正确输出调整大小的图片 ("contains errors")。

这是我的代码,我不知道哪里出了问题:

<?php   
header('Content-Type: image/jpeg');

$photos = glob($_GET['a'] . '/*.*');
$img = imagecreatefromjpeg($photos[array_rand($photos)]);

list($width, $height) = getimagesize($img);
if($width > $height) {
    $newWidth = 250;
    $newHeight = 250*$height/$width;
}
else {
    $newHeight = 250;
    $newWidth = 250*$width/$height;
}

$tmp = imagecreatetruecolor($newWidth, $newHeight);
imagecopyresampled($tmp, $img, 0, 0, 0, 0, $newWidth, $newHeight, $width, $height);

// Output the image
imagejpeg($tmp);
?>

函数getimagesize()需要文件名,而不是图像资源。它发出警告,这就是图像无效的原因,因为在图像二进制文件之前有一个字符串。

$photos = glob($_GET['a'] . '/*.*');
$filename = $photos[array_rand($photos)] ;
$img = imagecreatefromjpeg($filename);
list($width, $height) = getimagesize($filename);

或使用 imagesx() and imagesy() 使用 $img 获取图像大小。

$photos = glob($_GET['a'] . '/*.*');
$img = imagecreatefromjpeg($photos[array_rand($photos)]);
$width = imagesx($img);
$height = imagesy($img);