![](/img/trans.png)
[英]How to catch invalid image when using PHP imagecreatefromstring
[英]PHP export image as the same type (PNG, JPG, etc) when using imagecreatefromstring()
我有一个PHP函数,该函数接受任意字符串并从中创建图像资源,从而自动检测图像格式,如下所示:
$im = imagecreatefromstring($image_data_string);
如您所知,当$image_data_string
包含任何受支持的图像类型(例如JPG,PNG等)时,这将创建$ im图像资源。
经过对$ im资源的一些操作(修改了一些像素等),我想再次以相同的格式返回图像字符串。 也就是说,如果数据字符串包含PNG图像,我想返回生成的PNG图像的字符串。 如果是JPG,那么我想以字符串形式将其作为JPG返回。
PHP支持imagejpeg()
或imagepng()
和其他函数,因此,如果我知道如何检测$ im资源的图像类型,那么我将一切imagepng()
。 有像imagesx()
和imagesy()
这样的函数可以返回$im
资源的宽度和高度,但是我找不到合适的函数来返回$im
资源的图像类型。
我想到的唯一方法是分析原始$image_data_string
字节,以便找出图像类型。 但是我更愿意为此目的使用本机PHP函数,该函数可以在$ im资源参数上工作。 有没有类似的东西?
谢谢
改用此代码
$imgdata = base64_decode($image_data_string);
$f = finfo_open();
$mime_type = finfo_buffer($f, $imgdata, FILEINFO_MIME_TYPE);
$im = imagecreatefromstring($image_data_string);
$filename = 'somerandomname';
switch($mime_type){
case 'image/png':
imagepng($image, $filename.'.png');
break;
default:
break;
}
imagedestroy($im);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.