$url = "http://baidu.com/img.png";
$path = "img.png";
$fp = fopen($path, 'w+');
$ch = curl_init();
curl_setopt($ch, CURLOPT_ENCODING,'gzip');
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 30);
curl_setopt($ch, CURLOPT_FILE, $fp); // 用于传输的文件流,默认是 STDOUT
$output = curl_exec($ch);
if ($output === false) {
	throw new \Exception("文件下载失败:$url");
} else {
	fclose($fp);
	curl_close($ch);
}
虽然下载成功了,但是打开图片后仅有原图的部分,另一部分显示为灰色。 怎么改进一下?或者是什么原因造成的。
|  |      1C02TobNClov1Dz56      2022-04-15 11:40:57 +08:00 没用过 php, 我猜是这个下载方法是异步的, 实际上没下完, 你就关闭流了. | 
|  |      2bixchen      2022-04-15 11:42:02 +08:00 整复杂了,直接 file_get_contents 获取文件流写入本地文件就行了 | 
|      3lait123      2022-04-15 11:49:19 +08:00 file_get_contents 会出现 https 的一些问题,所以还是的 curl | 
|  |      4skiy      2022-04-15 12:07:14 +08:00 via iPhone 前段时间才了解到 file_get_contents 的强大。非常好用。 | 
|  |      5sleepm      2022-04-15 12:15:16 +08:00 @lait123 https://www.php.net/stream_context_create file_get_contents 第三个参数是上下文 可以参考 https://github.com/JonnyBo71/office-module/blob/main/Helpers/OfficeFunctions.php#L113= 图片显示不正确,也有可能原图是 jpg ,然后存成了 png | 
|  |      6dzdh      2022-04-15 13:20:45 +08:00  1 经常碰到的一个问题。 取 response header 的 content-length 取到的图片内容做比对。小于就重新尝试下载。 | 
|  |      7dajj      2022-04-15 13:24:34 +08:00 是不是开启了 gzip 压缩的原因 , 通常原始的方式处理数据, 压缩了要自己解压 | 
|      8s609926202 OP @dajj gzip 压缩,是提示图片损坏吧,应该和 gzip 压缩无关 | 
|  |      9dajj      2022-04-15 17:44:17 +08:00  1 可以对比下字节数,有没有少了 | 
|  |      10lslqtz      2022-04-15 23:36:29 +08:00 最近同样遇到这个问题,是 file_get_contents ,中间没有报错。 | 
|  |      11lslqtz      2022-04-15 23:39:46 +08:00 @chengyiqun 这个方法是同步的,会阻塞线程。 |