开发者

JPEG Images Turn all black when converting from a PNG with PHP

The problem: When converting any PNG image into a JPEG, the image turns all black.

To start off, I've searched the internet and stackoverflow to find out how to do this. I've tried every method I could find in the PHP Manual and on Stack Overflow. The problem still exists. I'm using GD (don't have ImageMagick installed).

My code is below. This is the call to the function:

$tempImage = $dirPath.$filename.$tempMini.".jpg";           
createTempImage($sourcefile, $tempImage, $tempMini_width, $tempMini_height, 100);

I've commented out the different methods that I've tried.

function createTempImage($sourcefile, $setNewName, $maxwidth, $maxheight, $quality){

$fileInfoArray = getimagesize($sourcefile);
$imagetype = $fileInfoArray['mime'];

if($imagetype == 'image/jpeg'){
    $img = imagecreatefromjpeg($sourcefile);

}elseif($imagetype == 'image/gif'){
    $img = imagecreatefromgif($sourcefi开发者_StackOverflow社区le);

}elseif(($imagetype == 'image/png')||($imagetype == 'image/x-png')){
    $img = imagecreatefrompng($sourcefile);
}

$width = imagesx( $img );
$height = imagesy( $img );

if ($width > $maxwidth || $height > $maxheight){
    $factor = min(($maxwidth/$width),($maxheight/$height));
    $newwidth = round($width*$factor);
    $newheight = round($height*$factor);
} else {
    $newwidth = $width;
    $newheight = $height;
}   


$tmpimg = imagecreatetruecolor( $newwidth, $newheight );
imagecopyresampled($tmpimg, $img, 0, 0, 0, 0, $newwidth, $newheight, $width, $height );
imagejpeg($tmpimg, $setNewName, 100);

imagedestroy($tmpimg);
imagedestroy($img);

}

The following have also been attempted:

$white = imagecolorallocate($tmpimg, 255, 255, 255);
ImageFill($tmpimg, 0, 0, $white);
ImageSaveAlpha($tmpimg, false);
ImageAlphaBlending($tmpimg, false);
$white = imagecolorallocate($tmpimg,  255, 255, 255);
imagefilledrectangle($tmpimg, 0, 0, $newwidth, $newheight, $white);

Update: The top black box is the image result: http://twitpic.com/30ywf5


Just a couple of ideas:

  • $newHeight = $maxheight; seems to be a typo, "newheight" is spelled without the capital "H" throughout the code.

  • The code to determine the new size can be shortened sigificantly:

if ($width > $maxwidth || $height > $maxheight){
$factor = min(($maxwidth/$width),($maxheight/$height));
$newwidth = round($width*$factor);
$newheight = round($height*$factor); }

  • You use imagecopyresampled to create the new image - this only works in specific GD-versions ("version 2"), try to use imagecopyresized otherwise.


I seemed to have fixed the problem by recreating the whole function from scratch. Thank you guys for your input.

The problem was that PNG's weren't being uploaded. When executing the script with already uploaded URLs, it worked fine.

Thanks again.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜