首页 > 解决方案 > 使用 file_get_contents 从 url 获取图像但得到错误:无法打开流

问题描述

我想获取图像并调整其大小然后保存,但是当我使用 url 获取图像并获取图像的信息时,会弹出错误。

$content = file_get_contents('http://localhost//uploadImage/tipsImages/9a861a512bed4530456620c159e80220e9eaba7f.png');
            if (($img_info = getimagesize($content)) === FALSE)
                die("Image not found or not an image");

                $width = $img_info[0];
                $height = $img_info[1];
                if($width > 740){
                    switch ($img_info[2]) {
                        case IMAGETYPE_GIF  : $src = imagecreatefromgif($img);  break;
                        case IMAGETYPE_JPEG : $src = imagecreatefromjpeg($img); break;
                        case IMAGETYPE_PNG  : $src = imagecreatefrompng($img);  break;
                        default : die("Unknown filetype");
                    }
                    $img_info = pathinfo($link);
                    $new_name = 'small_'.$img_info['filename'];
                    $new_width = 740;
                    $ratio = $new_width/$width;
                    $new_height = $height*$ratio;
                    $tmp = imagecreatetruecolor(740, $new_height);
                    imagecopyresampled($tmp, $src, 0, 0, 0, 0, $new_width, $new_height, $width, $height);
                    $dst = realpath(dirname(__FILE__).'/../../');
                    imagejpeg($tmp, $dst.$new_name.".jpg");
                }

出来的错误是

无法打开流:没有这样的文件或目录

在行

如果 (($img_info = getimagesize($content)) === FALSE)

该链接绝对正确,因为当我将其复制到浏览器时它会显示图像

标签: php

解决方案


我发现导致错误的原因是 getimagesize 假设使用链接而不是内容


推荐阅读