你好,我有下面的代码来创建一个图像的缩略图,然后上传它。当我尝试上传下面的图像时,代码失败了,我不知道为什么。在这段代码之前,有一个主图像上传,它总是有效的,但上面的缩略图脚本大部分时间都有效,但由于某种原因,没有附带图像。代码失效,因此页面输出主图像上传成功,但缩略图永远不会上传,页面的其余部分也不会上传。
这个代码还会处理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 );
失败的图像
您的代码适用于您的图像,所以问题一定是输入变量的设置值。
正如评论中已经建议的那样,请检查您的PHP错误日志。如果没有显示任何异常,则需要逐行调试代码。
对于问题的第二部分:不,您的代码不适用于JPEG以外的图像。下面的更改将处理GIF、JPEG和PNG。
请注意,默认情况下,函数exif_imagetype()
可能不可用。在这种情况下,您需要在PHP配置中激活exif扩展。
$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;
}