目前,如果用户将照片发布/上传到我的 PHP 脚本,我会从这样的代码开始
getimagesize($_FILES['picture1']['tmp_name']);
然后我对它做了更多的事情,但我也在尝试能够从 URL 获取照片,并在可能的情况下使用我的其他现有代码对其进行处理。所以我想知道,如果我使用这样的东西
$image = ImageCreateFromString(file_get_contents($url));
然后我可以在我的 $image 变量上运行 getimagesize() 吗?
更新
我刚试过这个...
$url = 'http://a0.twimg.com/a/1262802780/images/twitter_logo_header.png';
$image = imagecreatefromstring(file_get_contents($url));
$imageinfo = getimagesize($image);
print_r($imageinfo);
但是没用,给了这个。
Warning: getimagesize(Resource id #4) [function.getimagesize]: failed to open stream: No such file or directory in
知道如何执行此操作或类似操作以获得我想要的结果吗?
最佳答案
我建议您采用这种方法:
// if you need the image type
$type = exif_imagetype($url);
// if you need the image mime type
$type = image_type_to_mime_type(exif_imagetype($url));
// if you need the image extension associated with the mime type
$type = image_type_to_extension(exif_imagetype($url));
// if you don't care about the image type ignore all the above code
$image = ImageCreateFromString(file_get_contents($url));
echo ImageSX($image); // width
echo ImageSY($image); // height
使用 exif_imagetype()
比 getimagesize()
快很多,ImageSX()
/ImageSY( )
,而且它们不返回数组,并且还可以在图像调整大小或裁剪后返回正确的图像尺寸。
此外,在 URL 上使用 getimagesize()
并不好,因为它比来自 PHP Manual 的替代方法 exif_imagetype()
消耗更多的带宽。 :
When a correct signature is found, the appropriate constant value will be returned otherwise the return value is FALSE. The return value is the same value that
getimagesize()
returns in index 2 butexif_imagetype()
is much faster.
那是因为 exif_imagetype()
只会读取数据的前几个字节。
关于php - PHP 中的 ImageCreateFromString 和 getimagesize,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2024789/