2013-03-08 55 views
0

我试图在PHP中调整图像大小,如果上传的图像太大。我创建了一个函数,应该调整的文件,然后(希望)返回数组 - 除了它不工作:(作为一个数组返回一个图像

private function _resizeImage($image, $width = 780, $height = 780) { 

    $imgDetails = GetImageSize($image["tmp_name"]); 

    // Content type 
    //header("Content-Type: image/jpeg"); 
    //header("Content-Disposition: attachment; filename=resized-$image"); 

    // Get dimensions 
    $width_orig = $imgDetails['0']; 
    $height_orig = $imgDetails['1']; 

    $ratio_orig = $width_orig/$height_orig; 

    if ($width/$height > $ratio_orig) { 
     $width = $height*$ratio_orig; 
    } else { 
     $height = $width/$ratio_orig; 
    } 

    // Resample 
    switch ($imgDetails['2']) 
    { 
     case 1: $newImage = imagecreatefromgif($image["tmp_name"]); break; 
     case 2: $newImage = imagecreatefromjpeg($image["tmp_name"]); break; 
     case 3: $newImage = imagecreatefrompng($image["tmp_name"]); break; 
     default: trigger_error('Unsupported filetype!', E_USER_WARNING); break; 
    } 

    if (!$newImage) { 
     // We get errors from PHP's ImageCreate functions... 
     // So let's echo back the contents of the actual image. 
     readfile ($image); 
    } else { 
     // Create the resized image destination 
     $thumb = @ImageCreateTrueColor ($width, $height); 
     // Copy from image source, resize it, and paste to image destination 
     @ImageCopyResampled ($thumb, $newImage, 0, 0, 0, 0, $width, $height, $width_orig, $height_orig); 
     // Output resized image 
     //ImageJPEG ($thumb); 
    } 

    // Output 
    $newFile = imagejpeg($thumb, null, 100); 
    return $newFile; 
} 

这是由叫做:

if($imgDetails['0'] > 780 || $imgDetails['1'] < 780) { 
    $file = $this->_resizeImage($file); // Resize image if bigger than 780x780 
} 

但我没有得到一个对象回来了,我不知道为什么。

+0

[imagejpeg](http://php.net/manual/en/function.imagejpeg.php)返回布尔值。不是一个对象。 – 2013-03-08 19:05:39

回答

1

由于Seain在评论中提到,imagejpeg返回一个布尔值。

bool imagejpeg (resource $image [, string $filename [, int $quality ]]) 

Returns TRUE on success or FALSE on failure. 

imagejpeg reference on php.net

此外,你有NULL作为第二个参数,将作为原始图像流输出图像。如果要将图像保存到某处,则需要为此参数提供一个文件名。

另一个说明 - 你应该打电话imagedestroy($newImage);释放你从gif/jpeg/png创建图像时分配的内存。拨打电话号码imagejpeg后,请执行此操作。

另外我建议你不要使用@运算符来压制你的错误。请尝试将这些错误记录到错误日志中。压制会让你更难调试你的代码,如果你有压制的关键性错误会完全杀死你的脚本,而没有指出原因。错误日志帮助。

+0

+1感谢您的解释。 – 2013-03-09 13:52:09

+0

我还是有点困惑。我如何为新图像创建$ _FILES对象?我应该手动构建阵列吗?我该如何运行'imagedestroy'?新的文件名...? – 2013-03-09 13:54:43

+0

在'$ newImage'上调用'imagedestroy',因为'$ newImage'是您在调用'imagecreatefromjpeg','imagecreatefrompng'或'imagecreatefromgif'时创建的图像资源标识符。 – ozz 2013-03-09 18:46:11