Nir*_*shi 4 php file-upload image file image-processing
我有以下代码
// load image and get image size
$img = imagecreatefrompng( "{$pathToImages}{$fname}" );
$width = imagesx( $img );
$height = imagesy( $img );
// calculate thumbnail size
$new_width = $imageWidth;
$new_height = 500;
// 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 );
Run Code Online (Sandbox Code Playgroud)
它在某些图像上可以正常工作..但是在某些图像上却显示错误
Warning: imagecreatefromjpeg() [function.imagecreatefromjpeg]: gd-jpeg: JPEG library reports unrecoverable error:
Warning: imagesx() expects parameter 1 to be resource, boolean given
Warning: imagesy() expects parameter 1 to be resource, boolean given
Run Code Online (Sandbox Code Playgroud)
我也启用了
gd.jpeg_ignore_warning = 1
在php.ini中
任何帮助表示赞赏。
根据(2010年2月)的博客文章,其实现中的错误imagecreatefromjpeg应返回,false但会引发错误。
解决方案是检查图像的文件类型(我删除了重复调用,imagecreatefromjpeg因为它完全多余;我们已经检查过正确的文件类型,并且如果由于其他原因导致错误,imagecreatefromjpeg则将false正确返回):
function imagecreatefromjpeg_if_correct($file_tempname) {
$file_dimensions = getimagesize($file_tempname);
$file_type = strtolower($file_dimensions['mime']);
if ($file_type == 'image/jpeg' || $file_type == 'image/pjpeg'){
$im = imagecreatefromjpeg($file_tempname);
return $im;
}
return false;
}
Run Code Online (Sandbox Code Playgroud)
然后,您可以像这样编写代码:
$img = imagecreatefrompng_if_correct("{$pathToImages}{$fname}");
if ($img == false) {
// report some error
} else {
// enter all your other functions here, because everything is ok
}
Run Code Online (Sandbox Code Playgroud)
当然,如果要打开png文件,也可以对png进行相同的操作(如代码所示)。实际上,通常您将检查文件真正具有的文件类型,然后在这三个文件(jpeg,png,gif)之间调用正确的函数。