PHP复制图像并在HTML中加载


PHP Copy image and load in HTML

我已经上传了一张图片到文件夹:

/var/www/uploads/img.png

使用相对路径

../uploads/img.png

然后我用以下代码加载图像:

$img = copy('../uploads/9', '/tmp/profile_picture');

返回真正的

我的谷歌搜索让我找到了这个:

<img src="/tmp/profile_picture" alt="profile_picture" />

我已经尝试过以上带有和不带有.png结尾的方法。仍然不起作用。

我只需要拿出一张图片并显示在一个图像标签中,我总是知道我的图像的确切路径和文件名。

编辑

在这个线程中的第一个答案之后,我尝试了以下操作:

$image = '../uploads/9';
$info = getimagesize($image);
// output the image
header("Content-Disposition: filename={$image};");
header("Content-Type: {$info["mime"]}");
header('Content-Transfer-Encoding: binary');
header('Last-Modified: ' . gmdate('D, d M Y H:i:s', time()) . ' GMT');
readfile($image);

我在这里称这个脚本为:

<img src="profile_picture.php" alt="profile_picture" />

我得了404。

我已经为$image 尝试了各种路径

感谢您的帮助。

步骤1:纠正您对copy()的使用

使用:
$img = copy('/tmp/profile_picture', '../uploads/9');相反

从PHP.net文档中,复制功能的格式为:

copy ( string $source , string $dest [, resource $context ] )

其中参数:
source«源文件的路径。

dest«目标路径。如果目标文件已经存在,它将被覆盖。

context«使用stream_context_create()创建的有效上下文资源。


步骤2(1):将图像上传到网络可访问的路径

你需要知道你的网络根。考虑以下文件夹结构:
/var/www«你的www根

/var/www/project1«你的www根

/var/www/project1/assets/img«您的项目的可公开访问的图像目录

然后将您的图像上传到上述路径:/var/www/project1/assets/img/img.png

并使用这样的图像(来自index.html):

<img src="/assets/img/img.png" alt="Image">


步骤2(2):或者将图像包装在php文件中

这需要一个自定义的php文件,它可以在图像标记中使用。

示例:
image.php

<?php
$image = '/var/www/uploads/img.png';
$info = getimagesize($image);
// output the image
header("Content-Disposition: filename={$image};");
header("Content-Type: {$info["mime"]}");
header('Content-Transfer-Encoding: binary');
header('Last-Modified: ' . gmdate('D, d M Y H:i:s', time()) . ' GMT');
readfile($image);
?>


index.html

<img src="image.php" alt="Image">

解释

这个选项只是将您的图像包装在php脚本中,然后调用该脚本。

如果图像无法公开访问和/或我必须进行一些检查,看看当前用户是否值得访问该图像,我就会使用此选项。

::大多数文件共享web应用程序使用

您可以这样做。

使用函数sys_get_temp_dir()将图像直接上传到临时文件夹。

然后

$path = '/tmp/profile_picture';
$imageData = file_get_contents($path);
// display in view
echo sprintf('<img src="data:image/png;base64,%s" />', base64_encode($imageData));