2

我正在使用 PHP 调整一些 jpeg 图像的大小和重新采样。它采用任何大于 500 像素 x 500 像素的图像,并使最大边为 500 像素。这应该相对简单,但每次我运行脚本时,它都会生成一个黑色 jpeg。创建的 jpeg 具有适当的尺寸,但不包括调整大小的图像。GD 库已启用,并且我已确保它正在查找原始图像。我一直在看这个代码块一天半没有运气,我没有看到什么?

    <?php
$testimage = 'SandyCayCaribbeanbeach.jpg';
$testfolder = "testimage/testimage.jpg";
list($orgwidth, $orgheight, $type, $attr) = getimagesize($testimage);

echo "org. width  " . $orgwidth . "px" . "<br />";
echo "org. height  " . $orgheight . "px" . "<br />";

if($orgwidth > 500 || $orgheight > 500){
    if($orgwidth > $orgheight){
        header('Content-type: image/jpeg');
        $ratio = $orgwidth/500;
        $newwidth = floor($orgwidth/$ratio);
        $newheight = floor($orgheight/$ratio);

        $image_p = imagecreatetruecolor($newwidth, $newheight);
        $image = imagecreatefromjpeg($testimage);
        imagecopyresampled($image_p, $image, 0, 0, 0, 0, $newwidth, $newheight, $width, $height);

        imagejpeg($image_p, $testfolder, 100);
    }
    else{
        header('Content-type: image/jpeg');
        $ratio = $orgheight/500;
        $newheight = floor($orgheight/$ratio);
        $newwidth = floor($orgwidth/$ratio);

        $image_p = imagecreatetruecolor($newwidth, $newheight);
        $image = imagecreatefromjpeg($testimage);
        imagecopyresampled($image_p, $image, 0, 0, 0, 0, $newwidth, $newheight, $width, $height);

        imagejpeg($image_p, $testfolder, 100);
    }
}
    ?>
4

4 回答 4

2

首先确保您打开了错误报告。还要确保它可以找到源图像“SandyCayBaribbeanbeach.jpg”。

在处理图像大小调整之前进行简单if(file_exists())检查将有助于捕获错误。

于 2011-02-02T01:22:16.687 回答
2

我发现我必须指定图像的完整路径而不是URL,即

/path/to/image.jpg

代替

http://www.blah.com/image.jpg

让它正常工作。希望它可以帮助某人。

于 2011-10-26T22:01:32.860 回答
0

仔细检查以确保您的源图像确实是 JPEG。如果您运行的是 Windows,请在 MS Paint 中打开它并重新保存为 JPEG。这将有助于排除它是不同格式的可能性。

于 2011-02-02T01:20:40.233 回答
0

我最近在我的一段代码中也为此奋斗了一段时间,发现如果未定义尺寸,imagecopyresampled 甚至会返回 1。确保设置了源高度和宽度。

于 2011-02-02T19:58:15.100 回答