如何从 PHP 中的本地目录加载图像?
How can I load an image from a local directory in PHP?
我的设置(或路径)如下:
|Home
|ftpUsername
|assets
|images.png
|script.php
|mydomain.com
|index.php
index.php位于mydomain.com,其中包括script.php 在 /home/ftpUsername/assets 中没有问题。
script.php 使用 包含在 index.php 中include() 函数。
我的问题是,如何让 PHP 加载 /home/ftpUsername/assets/ 到 [=54= 中的图像(png 格式) ]?
换一种说法:
如何在 script.php 中加载 /home/ftpUsername/assets/myimage.png?
注意:/home/ftpUsername/mydomain.com/ 是活动目录(在线附加到域)而 home/ftpUsername/assets/ 不是(服务器上的本地目录)。
我尝试使用 img src="/home/ftpUsername/assets/myimage.png" 直接从路径加载它,但没有成功,无论是否使用反斜杠。
从script.php,你需要读取,然后输出PNG图像(传递正确的mimetype,所以它会被识别为图像)。
您可以使用 readfile or even file_get_contents 读取文件流,如下所示:(我假设您将通过 $_GET 'image' 传递图像名称。/script.php?image=imagename.png
并使用 no_image.png
作为备用。
header("Content-Type:image/png"); //passing the mimetype
$image = '/home/ftpUsername/assets/' . $_GET['image'];
if(is_file($image) || is_file($image = "/home/ftpUsername/assets/no_image.png"))
readfile($image);
这样,您可以直接在您的 img src 中 link 您的 script.png,就像这样:
<img src="script.php?image=imagename.png" alt="" />
您的 script.php 就像图像一样。
我的设置(或路径)如下:
|Home
|ftpUsername
|assets
|images.png
|script.php
|mydomain.com
|index.php
index.php位于mydomain.com,其中包括script.php 在 /home/ftpUsername/assets 中没有问题。
script.php 使用 包含在 index.php 中include() 函数。
我的问题是,如何让 PHP 加载 /home/ftpUsername/assets/ 到 [=54= 中的图像(png 格式) ]?
换一种说法:
如何在 script.php 中加载 /home/ftpUsername/assets/myimage.png?
注意:/home/ftpUsername/mydomain.com/ 是活动目录(在线附加到域)而 home/ftpUsername/assets/ 不是(服务器上的本地目录)。
我尝试使用 img src="/home/ftpUsername/assets/myimage.png" 直接从路径加载它,但没有成功,无论是否使用反斜杠。
从script.php,你需要读取,然后输出PNG图像(传递正确的mimetype,所以它会被识别为图像)。
您可以使用 readfile or even file_get_contents 读取文件流,如下所示:(我假设您将通过 $_GET 'image' 传递图像名称。/script.php?image=imagename.png
并使用 no_image.png
作为备用。
header("Content-Type:image/png"); //passing the mimetype
$image = '/home/ftpUsername/assets/' . $_GET['image'];
if(is_file($image) || is_file($image = "/home/ftpUsername/assets/no_image.png"))
readfile($image);
这样,您可以直接在您的 img src 中 link 您的 script.png,就像这样:
<img src="script.php?image=imagename.png" alt="" />
您的 script.php 就像图像一样。