在PHP中使用ImageCreateFromString和getimagesize

时间:2010-01-08 00:54:04

标签: php image-processing

目前,如果用户POST /上传照片到我的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

我知道如何才能做到这一点或类似的事情来获得我追求的结果?

4 个答案:

答案 0 :(得分:10)

我建议您遵循这种方法:

// 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()也是如此,而且它们不会返回数组例如,在调整图像大小或裁剪图像后,也可以返回正确的图像尺寸。

另外,在网址上使用getimagesize()并不好,因为它会从PHP Manual中消耗比{{3}}更多的带宽exif_imagetype()

  

找到正确的签名后,即可   适当的恒定值将是   否则返回值为   假。返回值是相同的   getimagesize()返回的值   索引2但是exif_imagetype()很多   更快。

那是因为exif_imagetype()只会读取数据的前几个字节。

答案 1 :(得分:1)

如果您已经拥有图像资源,则可以使用imagesx和imagesy函数获得大小。

答案 2 :(得分:0)

getimagesize可以与HTTP一起使用。

  

文件名 - 它可以使用其中一个支持的流引用本地文件或(配置允许)远程文件。

因此

$info = getimagesize($url);
$image = ImageCreateFromString(file_get_contents($url));

应该没问题。

答案 3 :(得分:0)

不确定这是否会有所帮助,但我遇到了类似的问题,结果发现我的主机控制的防火墙阻止了来自我服务器的传出http连接。

他们更改了防火墙设置。然后我的代码工作了。

顺便说一句:当我在许多网址上尝试使用file_get_contents()时,我认为这可能是一个问题,但没有一个工作!