PHP: How to output image files?

别等时光非礼了梦想. 提交于 2019-12-11 06:58:36

问题


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.

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

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.


回答1:


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

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.

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.

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

So a brief example:

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

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

PHP file says:

<?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.

Useful references:

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

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



来源:https://stackoverflow.com/questions/29032405/php-how-to-output-image-files

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!