使用 curl 方式获取远程链接的图片时,获取的图片信息并不完整,临时保存到本地,打开是不正确的图片格式。
并进一步导致 PHP 代码读取图片内容报错,检查后发现设置 CURLOPT_ENCODING 即可
private function getImgByCurl($url)
{
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_ENCODING, ''); // 添加这一行
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 30);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($ch, CURLOPT_SSLVERSION, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
$file = curl_exec($ch);
if (curl_exec($ch) === false) {
$errmsg = 'Get remote-image failed: ' . curl_error($ch);
} else $errmsg = 'ok';
curl_close($ch);
return ['errmsg' => $errmsg, 'file' => $file];
}
/**
* The contents of the "<em>Accept-Encoding: </em>" header. This enables decoding of the response.
* Supported encodings are "identity", "deflate", and "gzip".
* If an empty string, "", is set, a header containing all supported encoding types is sent.
* @link https://www.php.net/manual/en/function.curl-setopt.php
*/
define('CURLOPT_ENCODING', 10102);
了解 王坤的博客 的更多信息
订阅后即可通过电子邮件收到最新文章。