在PHP中使用ImageCreateFromString和getimagesize

Jas*_*vis 4 php image-processing

目前,如果用户POST /上传照片到我的PHP脚本,我开始使用这样的代码

getimagesize($_FILES['picture1']['tmp_name']);
Run Code Online (Sandbox Code Playgroud)

然后我做了很多其他的东西,但我也试图从URL获取一张照片并用我的其他现有代码处理它,如果可以的话.所以我想知道,我使用这样的东西

$image = ImageCreateFromString(file_get_contents($url));
Run Code Online (Sandbox Code Playgroud)

我能在我的$ image变量上运行getimagesize()吗?



UPDATE

我刚试过这个......

$url = 'http://a0.twimg.com/a/1262802780/images/twitter_logo_header.png';
$image = imagecreatefromstring(file_get_contents($url));
$imageinfo = getimagesize($image);
print_r($imageinfo);
Run Code Online (Sandbox Code Playgroud)

但它没有用,给了这个.

Warning: getimagesize(Resource id #4) [function.getimagesize]: failed to open stream: No such file or directory in
Run Code Online (Sandbox Code Playgroud)

知道如何做到这一点或类似的东西,以获得我追求的结果?

Ali*_*xel 11

我建议你按照这种方法:

// 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
Run Code Online (Sandbox Code Playgroud)

使用exif_imagetype()比使用快得多getimagesize(),同样适用于ImageSX()/ ImageSY(),而且它们不会返回数组,并且还可以在调整图像大小或裁剪后返回正确的图像尺寸.

此外,使用getimagesize()上的网址是不是一件好事,因为它会消耗大量的带宽比选择exif_imagetype(),从PHP手册:

找到正确的签名后,将返回相应的常量值,否则返回值为FALSE.返回值与getimagesize()索引2中返回的值相同,但exif_imagetype()速度更快.

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