2011-03-21 97 views
0

我有一个脚本来调整上传的图像,但是当我使用它,它只是返回一个黑色的正方形。所有错误消息都指向这个函数:Imagecreatefromjpeg返回黑色图像后调整

function resizeImage($image,$width,$height,$scale) { 
    $newImageWidth = ceil($width * $scale); 
    $newImageHeight = ceil($height * $scale); 
    $newImage = imagecreatetruecolor($newImageWidth,$newImageHeight); 
    $source = imagecreatefromjpeg($image); 
    imagecopyresampled($newImage,$source,0,0,0,0,$newImageWidth,$newImageHeight,$width,$height); 
    imagejpeg($newImage,$image,90); 
    chmod($image, 0777); 
    return $image; 
} 

我的错误日志:

PHP Warning: imagecreatefromjpeg() [<a href='function.imagecreatefromjpeg'>function.imagecreatefromjpeg</a>]: gd-jpeg: JPEG library reports unrecoverable error 
PHP Warning: imagecreatefromjpeg() [<a href='function.imagecreatefromjpeg'>function.imagecreatefromjpeg</a>]: 'img/[hidden].jpg' is not a valid JPEG file 
PHP Warning: imagecopyresampled(): supplied argument is not a valid Image resource 

回答

0

根据Marc B的回答,你可能会检查该文件是否为JPG文件。 (JPEG,JPG,jpg,jpeg扩展名)。

它可能是这样的:

$file = explode(".", $_POST['file']); 
$file_ext = $file[count($file)]; // Get the last thing in the array - in this way the filename can containg dots (.) 
$allowed_ext = array('jpg', 'JPG', 'jpeg', 'jpg'); 

if(in_array($file_ext, $allowed_ext) 
{ 
    // The code for creating the image here. 
} 
+0

感谢您的支持! – iamandrus 2011-03-21 21:51:54

0
  1. 检查是否imagecreatetruecolor成功。如果新图像“大”,它可能会超过PHP memory_limit。如果因任何原因失败,此函数返回FALSE。
  2. 同上同imagecreatefromjpeg()。这两个单独的图像可能符合内存限制,但可能会过大。源图像也可能不存在。该函数返回FALSE失败,如果有任何理由
  3. 检查是否imagecopyresampled()失败 - 它也失败时返回FALSE。
  4. 检查imagejpeg()失败 - 也许你没有在任何文件你在$image指定写权限。再次,这个函数在失败时返回FALSE。
+0

我刚添加的错误日志。 – iamandrus 2011-03-21 20:19:30

+0

你走了......你想要缩放的原始图像不能被GD读取。或者它不是JPG,或者是(也许)是CMYK jpeg,或者在文件中包含其他内容以使GD认为它不是jpg。 – 2011-03-21 20:20:54