开发者

PHP create image without declaring image header for entire page

I want to create several images with PHP on my webpage. Is there a way to do this withou开发者_如何学Got creating each image in its own PHP file and then placing the URLs to these files in img tags?


I suggest you take the image and encode it to BASE64 using base64_encode(), this way you can insert the image data directly into the HTML markup (safer than injecting binary).

The process is described at this site. But in a nutshell just have a tag that looks like the following (everything after the "base64," is the encoded data):

<img src="data:image/gif;base64,R0lGODlhEAAOALMAAOazToeHh0tLS/7LZv/0jvb29t/f3//Ub/
/ge8WSLf/rhf/3kdbW1mxsbP//mf///yH5BAAAAAAALAAAAAAQAA4AAARe8L1Ekyky67QZ1hLnjM5UUde0ECwLJoExKcpp
V0aCcGCmTIHEIUEqjgaORCMxIC6e0CcguWw6aFjsVMkkIr7g77ZKPJjPZqIyd7sJAgVGoEGv2xsBxqNgYPj/gAwXEQA7" 
width="16" height="14" alt="embedded folder icon">


No, there's no other way as the content-type header is page-wide; you can't have different content types for one page. But you don't need to have one PHP file for each of your images, you can do it like this:

<img src="image_generator.php" />

And in image_generator.php, you declare the image header and output the image, and possibly generate it according to a query string. For example, you can append a image id to the URL:

<img src="image_generator.php?id=100" />

Then in image_generator.php, just select the image data according to $_GET['id'] and generate it.


You either use a header and output directly the image bytes, or write them to a file and put them in the src attribute, there is no other way.

A neat approach is to have a specific image creation script you reference in your src attribute:

<img src="imagecreator.php?img=43" />

In this script you obviously should use the header() approach and output the image bytes.

<?php
$im = imagecreatefrompng($_GET['img'].".png"); //Silly example

header('Content-type: image/png');

imagepng($im);
imagedestroy($im);
?>


A possible solution, to not have several PHP scripts, would be to have only one, that would be able to generate a different image depending on a parameter.

For instance, some pseudo-code like this one should make what I mean more clear :

$id_img = intval($_GET['id']);
switch ($id_img) {
    case '1':
        // generate image 1
        break;
    case '2':
        // generate image 2
        break;
    case '3':
        // generate image 3
        break;
    default:
        // send some kind of 404 error
}


And your <img> tags would look a bit like these :

<img src="http://yoursite.com/img-generator.php?id=1" alt="..." />
<img src="http://yoursite.com/img-generator.php?id=2" alt="..." />


Still, each time the PHP script is generated, it can only return the headers an data for only one image -- which means it has to be called several times.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜