PHP:如何输出图像文件? [英] PHP: How to output image files?

查看:80
本文介绍了PHP:如何输出图像文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用PHP将图像添加到动态生成的页面(我使用自己的模板系统)中.

I would like to add images to a dynamically generated page (I use my own template system) with PHP.

注意:出于安全原因,我对图片访问进行了监管.

NOTE: I regulate image access for security reason.

包含图像的文件夹位于网站根目录上方,因此无法通过HTML链接访问.

The folder that contains the images is above the site root, therefore not accessible by HTML links.

我相信有一种方法,其中PHP将文件作为资源返回,并在标头中指定类型,并且(如果我错了,请纠正我)为该 imagejpeg()设计的函数>.

I believe there is a method in which PHP returns a file as a resource, specifying the type in a header, and (correct me if I am wrong) a function specifically designed for that imagejpeg().

请告知,并在可能的情况下写一个简单的示例.

Please advise, and if possible write a simple example.

推荐答案

输出图像文件所需要做的是按顺序进行:

What you need to do to output image files is in order:

PHP从文件中加载图像,这是 file_get_contents fopen 来打开和访问文件本身.如果文件是特定的图像文件,则可以使用 imagecreatefromjpeg()打开文件,这样做会从JPEG源生成图像文件.

PHP loads the image from the file, this is file_get_contents or otherwise fopen to open and access the file itself. If the file is a specific image file you can open the file with imagecreatefromjpeg() which will do just that, generate an image file from a JPEG source.

然后,一旦从文件系统上的任何位置(包括Web根目录之外的目录)加载了文件,PHP便可以输出上面第1点捕获的数据,并带有一些HTTP标头并直接引用已加载的映像.

Then, once the file is loaded from anywhere on your filesystem, including directories outside of your web root, PHP can output the data caught in point 1, above, with some HTTP Headers and direct reference to the loaded image.

注意:这表示此PHP文件的唯一输出是图像,因此在这种情况下,file.php === image.jpg.

NOTE: this means that the sole output of this PHP file is the image, so file.php === image.jpg in this case.

举个简单的例子:

图像存储在/home/images/image1.jpg

image is stored in /home/images/image1.jpg

PHP文件从/home/site/imagecall.php运行

PHP file runs from /home/site/imagecall.php

PHP文件说:

<?php
if (file_exists('/home/images/image1.jpg')){
    $image = imagecreatefromjpeg('/home/images/image1.jpg');
    if ($image){
         header('Content-Type: image/jpeg');
         imagejpeg($image);
         imagedestroy($image);
    }  
    else {
        die("Image could not be loaded");
    }
}

这是您的起点,绝不是绝对的指导.探索.

This is a starting point for you and by no means an absolute guide. Explore.

有用的参考文献:

http://php.net/manual/en/function.imagecreatefromjpeg.php

http://php.net/manual/en/function.file-get-contents.php

这篇关于PHP:如何输出图像文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆