2010-10-26 99 views
2

问题:将任何PNG图像转换为JPEG图像时,图像全部变为黑色JPEG图像使用PHP转换PNG图像时转为全黑色

首先,我搜索了互联网和stackoverflow,以了解如何做到这一点。我已经尝试了所有可以在PHP手册和堆栈溢出中找到的方法。问题依然存在。我使用GD(没有安装ImageMagick)。

我的代码如下。这是对功能的调用:

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

我已经评论了我尝试过的不同方法。

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($sourcefile); 

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

}

下也已经尝试:

$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); 

更新:顶部黑匣子是图像结果:http://twitpic.com/30ywf5

+0

在MIME检测中添加最后的else语句: 'else die(“unknown format”);' – jmz 2010-10-26 07:55:04

+0

你能举一个例子PNG吗?你是否尝试过来自不同来源的各种PNG? – 2010-10-26 08:20:59

+1

每次我尝试从Google获取新的.PNG图像时。 顶部框是图像结果:http://twitpic.com/30ywf5 – stwhite 2010-10-26 08:27:15

回答

0

我似乎已经从头开始重新创建整个功能,解决了这个问题。谢谢你们的意见。

问题是PNG没有被上传。使用已上传的URL执行脚本时,它工作正常。

再次感谢。

1

只是一对夫妇的想法:

  • $newHeight = $maxheight;似乎是一个错字,“newheight”在整个代码中拼写时没有大写“H”。

  • 的代码,以确定新的大小可以sigificantly缩短:

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

  • 您使用imagecopyresampled到CRE吃了新的图像 - 这只适用于特定的GD版本(“版本2”),否则请尝试使用imagecopyresized
+0

感谢您的帮助。我很感激。 不幸的是,imagecopyresized没有为我工作。 图像仍然是完全黑色的。我每次都选择新的图像,都是.PNG格式。 – stwhite 2010-10-26 08:17:32

+0

你可能想看看这段代码:http://www.beehave。de/forum/aktuelle-version-von-uploadpic-1-3-9-t527.html它是phpBB软件的附件,可以上传图片。上传PNG并调整大小会导致(不是黑色)JPG,因此您可以通过分析如何处理上传/调整大小来找到解决方案。 – Select0r 2010-10-26 08:58:06

+0

你忘了在缩短的代码后面的'else'语句中。如果你这样做,$ newwidth和$ newheight可能是NULL。 – Select0r 2010-10-26 11:44:38

相关问题