开发者

imagecopyresampled makes black box but not resampled image

I am working to resize and resample some jpeg images using PHP. It take any image greater than 500px by 500px and make the largest side 500px. This should be relatively simple but every time I run the script it makes a black jpeg. The jpeg created has the proper dimensions but does not include the resized image. The GD library is enabled, and I have made sure it is finding the orig开发者_开发问答inal image. I've been looking at this block of code for a day and half with no luck, what am I not seeing?

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


Firstly make sure you have error reporting turned on. Also make sure it can find the source image "SandyCayBaribbeanbeach.jpg".

A simple if(file_exists()) check before handling the image resizing will help trap errors.


I found that I had to specify a full path to the image, not a URL i.e.

/path/to/image.jpg

instead of

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

to get this to work properly. Hope it helps someone.


Double-check to make sure your source image is truly a JPEG. If you are running Windows, open it up in MS Paint and re-save as a JPEG. This will help rule out the possibility of it being a different format.


I also fought this for a while in a piece of my code recently, and found that imagecopyresampled will even return 1 if the dimensions are not defined. Make sure that your source height and width are set.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜