【问题标题】:php return image from urlphp从url返回图片
【发布时间】:2015-03-30 06:49:56
【问题描述】:

我想通过http://placehold.it/500x500 之类的 URL 返回图像。 我有我的 URL http://example.inc/assets/image/35345,它在控制器上调用一个动作。控制器从数据库中获取一些数据(名称、id 等)以及图像内容的二进制字符串。

在前端站点,我有我的 img 标签,我想在我的 src 属性中调用 url。

<img src="http://example.inc/assets/image/35345">

更多信息,我使用 slim PHP 框架,我的服务器是 ubuntu 13.x 系统(vagrant 等)。我是一个典型的前端开发人员,没有很好的技能@PHP。

以下 sn-ps 作品:

$file = fopen($name, 'wb');
fwrite($file, $binaryData);
fclose($file);

但我不想在目录中生成文件。这可能吗?

编辑:设置了 Content-Type 和 Content-Length 标头,这不是问题。

【问题讨论】:

  • 您想要达到的目标。你想显示上传的图片吗?我发现这个问题有点混乱。
  • 我想要 plachold.it/500x500 给我的相同结果,网址给我一张图片,我想给 img 标签一个返回图片的网址。

标签: php image dynamic-image-generation


【解决方案1】:

获取图像的内容,base_64 对其进行编码,然后返回一个 base64 图像。

$file = file_get_contents($name);
list($width, $height, $type, $attr) = getimagesize($file);
echo '<img src="data:image/'.$type.';'.base64_encode($file).'"/>';

【讨论】:

  • 我没有文件,我只有一个包含文件名的数据库条目,例如“200.jpg”和filecontent =“djhfkagkjhvköfghfsajhdhgdöoa[...]”二进制数据。
【解决方案2】:
  1. 您应该使用类似这样的方式上传目录中的图像。此代码会将您的图片上传到目录中。

if ($_FILES['file']['name'] != "") {
            $filename = $_FILES['file']['name']; //getting name of the file from form
            $filesize = $_FILES['file']['size'];
            $info = new SplFileInfo($filename);
            $ext = $info->getExtension();
            $filesize1 = ($filesize * .0009765625) * .0009765625;
            if (!($ext == 'jpg' || $ext == 'png' || $ext == 'jpeg')) {
                //set some error message and redirect
            }
            if ($filesize1 >= 5.0) {
                 //set message image size should be less than 5 mb
            }

            $target_path = $_SERVER['DOCUMENT_ROOT'] . "../images/profile_images/";
            move_uploaded_file($_FILES['file']['tmp_name'], "$target_path" . $_FILES['file']['name']) or
                    die("Could not copy file!");
        }
  1. 在数据库中插入图像名称(带扩展名)。(此处为$filename)
  2. 从数据库中获取图像名称并存储在变量中(此处为$profile_image),在img src中使用它。

&lt;a href='../images/profile_images/$profile_image'&gt;&lt;img alt='Avatar' src='../images/profile_images/$profile_image'&gt;&lt;/a&gt;
  1. 您只能使用 Anchor 标记在浏览器的另一个选项卡中的图像上重定向用户。

希望这个答案对您有所帮助。

【讨论】:

    【解决方案3】:

    因为我有一个带有 iso charset 的 mssql 数据库,所以我已将所有结果都转换为 utf-8,问题是字节串也转换为 utf-8。

    在不转换字节串后,我还返回了字节串并将标题内容类型设置为图像/扩展

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-11-16
      • 1970-01-01
      • 2016-10-04
      • 1970-01-01
      • 2020-05-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多