代码之家  ›  专栏  ›  技术社区  ›  bur

PHP图像大小调整不起作用

  •  0
  • bur  · 技术社区  · 7 年前

    我正在尝试从JPG图像创建缩略图,但无法正确输出调整大小的图像(“包含错误”)。

    这是我的代码,我不知道怎么了:

    <?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);
    ?>
    
    1 回复  |  直到 7 年前
        1
  •  1
  •   Syscall - leaving SO... Juhzuri    7 年前

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

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

    或使用 imagesx() imagesy() 要获取图像大小,请使用 $img .

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