V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
s609926202
V2EX  ›  PHP

PHP 下载远程图片到本地后只显示部分内容是什么情况?

  •  
  •   s609926202 · 2022-04-15 11:34:15 +08:00 · 1950 次点击
    这是一个创建于 736 天前的主题,其中的信息可能已经有所发展或是发生改变。
    $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);
    }
    

    虽然下载成功了,但是打开图片后仅有原图的部分,另一部分显示为灰色。 怎么改进一下?或者是什么原因造成的。

    11 条回复    2022-04-15 23:39:46 +08:00
    chengyiqun
        1
    chengyiqun  
       2022-04-15 11:40:57 +08:00
    没用过 php, 我猜是这个下载方法是异步的, 实际上没下完, 你就关闭流了.
    bixchen
        2
    bixchen  
       2022-04-15 11:42:02 +08:00
    整复杂了,直接 file_get_contents 获取文件流写入本地文件就行了
    lait123
        3
    lait123  
       2022-04-15 11:49:19 +08:00
    file_get_contents 会出现 https 的一些问题,所以还是的 curl
    skiy
        4
    skiy  
       2022-04-15 12:07:14 +08:00 via iPhone
    前段时间才了解到 file_get_contents 的强大。非常好用。
    sleepm
        5
    sleepm  
       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
    dzdh
        6
    dzdh  
       2022-04-15 13:20:45 +08:00   ❤️ 1
    经常碰到的一个问题。

    取 response header 的 content-length 取到的图片内容做比对。小于就重新尝试下载。
    dajj
        7
    dajj  
       2022-04-15 13:24:34 +08:00
    是不是开启了 gzip 压缩的原因 , 通常原始的方式处理数据, 压缩了要自己解压
    s609926202
        8
    s609926202  
    OP
       2022-04-15 13:52:49 +08:00
    @dajj gzip 压缩,是提示图片损坏吧,应该和 gzip 压缩无关
    dajj
        9
    dajj  
       2022-04-15 17:44:17 +08:00   ❤️ 1
    可以对比下字节数,有没有少了
    lslqtz
        10
    lslqtz  
       2022-04-15 23:36:29 +08:00
    最近同样遇到这个问题,是 file_get_contents ,中间没有报错。
    lslqtz
        11
    lslqtz  
       2022-04-15 23:39:46 +08:00
    @chengyiqun 这个方法是同步的,会阻塞线程。
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   2657 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 29ms · UTC 15:28 · PVG 23:28 · LAX 08:28 · JFK 11:28
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.