2014-10-30 109 views
-1

你好,我有以下代码来创建一个图像的缩略图,然后上传它。当我尝试上传下面附加的图片时,代码失败,我不知道为什么。在此代码之前,有一个主要图像上传总是有效的,但上面的缩略图脚本在大多数情况下都能正常工作,但由于某些原因不会附加图像。代码死了,所以页面输出主要图片上传的成功,但缩略图从未上传,页面的其余部分也没有。Php图片上传失败,并使用imagecreatefromjpeg来处理PNG和BMP文件?

此代码还会处理jpeg以外的图像吗?如果它不会如何去处理像bmp和png这样的其他文件类型?

// load image and get image size 
    $img = imagecreatefromjpeg($upload_path . $filename); 
    $width = imagesx($img); 
    $height = imagesy($img); 

    // calculate thumbnail size 
    $new_height = $thumbHeight; 
    $new_width = floor($width * ($thumbHeight/$height)); 

    // create a new temporary image 
    $tmp_img = imagecreatetruecolor($new_width, $new_height); 

    // copy and resize old image into new image 
    imagecopyresized($tmp_img, $img, 0, 0, 0, 0, $new_width, $new_height, $width, $height); 

    // save thumbnail into a file 
    imagejpeg($tmp_img, $upload_paththumbs . $filename); 

Image that fails

+2

请解释一下你的*“的代码失败” * – Phil 2014-10-30 02:35:53

+0

在此之前的代码中有一个主要的图片上传总是工作,但上面的缩略图脚本工作的大部分时间,但无法与安装的图像是什么意思因为某些原因。代码死了,所以页面输出主要图片上传的成功,但缩略图从未上传,页面的其余部分也没有。 – Munnaz 2014-10-30 02:41:26

+0

听起来像你没有看到错误。在你的'php.ini'文件来实现正确的错误报告'的error_reporting = E_ALL'和'的display_errors = On'并重新启动Web服务器 – Phil 2014-10-30 02:43:30

回答

0

您的代码对我的作品与你的形象,所以这个问题必须与您输入变量的设定值。

正如评论中的建议,检查你的PHP错误日志。如果没有显示任何异常,则需要逐行调试代码。

对于你的问题的第二部分:不,你的代码也不会比JPEG图像等工作。下面的更改将处理GIF,JPEG和PNG。

注意,功能exif_imagetype()可能不会被默认使用。在这种情况下,您需要在您的PHP配置中使用activate the exif extension

$upload_path = './'; 
$filename = 'b4bAx.jpg'; 
$upload_paththumbs = './thumb-'; 
$thumbHeight = 50; 

switch (exif_imagetype($upload_path . $filename)) { 
    case IMAGETYPE_GIF: 
     imagegif(
      thumb(imagecreatefromgif($upload_path . $filename), $thumbHeight), 
      $upload_paththumbs . $filename 
     ); 
     break; 
    case IMAGETYPE_JPEG: 
     imagejpeg(
      thumb(imagecreatefromjpeg($upload_path . $filename), $thumbHeight), 
      $upload_paththumbs . $filename 
     ); 
     break; 
    case IMAGETYPE_PNG: 
     imagepng(
      thumb(imagecreatefrompng($upload_path . $filename), $thumbHeight), 
      $upload_paththumbs . $filename 
     ); 
     break; 
    default: 
     echo 'Unsupported image type!'; 
} 

function thumb($img, $thumbHeight) { 
    // get image size 
    $width = imagesx($img); 
    $height = imagesy($img); 

    // calculate thumbnail size 
    $new_height = $thumbHeight; 
    $new_width = floor($width * ($thumbHeight/$height)); 

    // create a new temporary image 
    $tmp_img = imagecreatetruecolor($new_width, $new_height); 

    // copy and resize old image into new image 
    imagecopyresampled($tmp_img, $img, 0, 0, 0, 0, $new_width, $new_height, $width, $height); 

    // return thumbnail 
    return $tmp_img; 
}