PHP cURL如何获得图像宽度?

时间:2016-04-23 17:18:21

标签: php image curl width

这是我到目前为止所尝试的:

$h = curl_init();
$headers = array(
"Range: bytes=0-700"
);
curl_setopt($h, CURLOPT_URL, $url);
curl_setopt($h, CURLOPT_HTTPHEADER, $headers);
curl_setopt($h, CURLOPT_RETURNTRANSFER, 1); //return the image value

$mh = curl_multi_init();
curl_multi_add_handle($mh, $h);

$running = null;
do {
   curl_multi_exec($mh, $running);
} while ($running > 0);

$raw = curl_multi_getcontent($h);
$im = imagecreatefromstring($raw);



 $width = imagesx($im);
    $height = imagesy($im);


var_dump($width);

每当我运行代码时,我都会收到此错误:

> ( ! ) Warning: imagecreatefromstring(): Data is not in a recognized
> format in
> C:\wamp\www\......funcs.php on
> line 399 Call Stack
> # Time    Memory  Function    Location 1  0.0022  294120  {main}( )   ..\...

如果你var_dump( $raw )说:

string '<html>

<head><title>302 Found</title></head>

<body bgcolor="white">

<center><h1>302 Found</h1></center>

<hr><center>BSWS/2.1</center>

</body>

</html>

' (length=157)

可能是什么问题......我现在花了6个多小时试图解决问题...请帮助。感谢

1 个答案:

答案 0 :(得分:3)

看起来您正在接收来自服务器的重定向,而cURL正在将此作为内容而不是图像本身。尝试使用CURLOPT_FOLLOWLOCATION选项。

所以:

curl_setopt($h, CURLOPT_URL, $url);
curl_setopt($h, CURLOPT_HTTPHEADER, $headers);
curl_setopt($h, CURLOPT_RETURNTRANSFER, 1); //return the image value

变为:

curl_setopt($h, CURLOPT_URL, $url);
curl_setopt($h, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($h, CURLOPT_HTTPHEADER, $headers);
curl_setopt($h, CURLOPT_RETURNTRANSFER, 1); //return the image value

此处cURL的完整选项列表:http://php.net/manual/en/function.curl-setopt.php

HTH