在PHP中使用ImageCreateFromString和getimagesize [英] ImageCreateFromString and getimagesize in PHP
问题描述
目前,如果用户POST /上传照片到我的PHP脚本,我开始使用这样的代码
Currently if a user POST/uploads a photo to my PHP script I start out with some code like this
getimagesize($_FILES['picture1']['tmp_name']);
然后我做了很多东西,但我也试图得到一张照片如果可以的话,从URL处理它与我的其他现有代码。所以我想知道,我使用的是这样的东西
I then do a LOT more stuff to it but I am trying to also be able to get a photo from a URL and process it with my other existing code if I can. SO I am wanting to know, I f I use something like this
$image = ImageCreateFromString(file_get_contents($url));
我可以在$ image变量上运行getimagesize()吗?
Would I be able to then run getimagesize() on my $image variable?
更新
我刚试过这个......
I just tried this...
$url = 'http://a0.twimg.com/a/1262802780/images/twitter_logo_header.png';
$image = imagecreatefromstring(file_get_contents($url));
$imageinfo = getimagesize($image);
print_r($imageinfo);
但它没有用,给了这个。
But it didnt work, gave this.
Warning: getimagesize(Resource id #4) [function.getimagesize]: failed to open stream: No such file or directory in
我知道如何做到这一点或类似的事情来获得我追求的结果?
Any idea how I can do this or something similar to get the result I am after?
推荐答案
我建议您遵循这种方法:
I suggest you follow this approach:
// 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( )
,加上它们不返回数组和也可以在调整图像大小或裁剪后返回正确的图像尺寸。
Using exif_imagetype()
is a lot faster than getimagesize()
, the same goes for ImageSX()
/ ImageSY()
, plus they don't return arrays and can also return the correct image dimension after the image has been resized or cropped for instance.
此外,在URL上使用 getimagesize()
并不好,因为它会消耗比替代 exif_imagetype更多的带宽()
,来自 PHP手册:
Also, using getimagesize()
on URLs isn't good because it'll consume much more bandwidth than the alternative exif_imagetype()
, from the PHP Manual:
当找到正确的签名时,
适当的常量值将返回
,否则返回值是
FALSE。返回值与
值相同,getimagesize()
返回
索引2但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()
只会读取数据的前几个字节。
That's because exif_imagetype()
will only read the first few bytes of data.
这篇关于在PHP中使用ImageCreateFromString和getimagesize的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!