您好我有以下代码来创建图像的缩略图然后上传它。当我尝试上传下面附带的图片时代码失败,我不知道为什么。在此代码之前有一个主图像上传,它始终有效,但上面的缩略图脚本大部分时间都可以工作,但由于某些原因没有附加图像。代码消失,因此页面输出主图像上传成功,但缩略图从不上传,页面的其余部分也没有。
此代码还会处理除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 );
答案 0 :(得分: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;
}