开发者

Image processing and output using GD in php

开发者 https://www.devze.com 2022-12-15 08:54 出处:网络
I want to control the display of images with the PHP GD library -- I am going to add some text to the bottom corner of it on the fly when a browser requests the image, rather than saving the text into

I want to control the display of images with the PHP GD library -- I am going to add some text to the bottom corner of it on the fly when a browser requests the image, rather than saving the text into the image.

I know that I can do this: set the MIME type in the header and then call imagepng(...) with the filename to just display the image to the browser, but how would I embed it in a document? Like,

<img src='somefile.php?i=1' ... />

do I just call imagepng with the filename but without setting the headers?

Also, if someone copies the image source out of the source code a开发者_JS百科nd navigates to it in the browser... what will happen if the headers aren't set? Will the image display as if the actual image was requested?


If you generate the image on somefile.php when a user tries to access that url directly the browsers output will be the image unless they don't specify the variable which contains the id/name of the image itself.

To use the image on html I just do <img src='somefile.php?f=FILENAME' /> to make it more readable (as long as you have relevant image names).

Make sure to handle a non specified access to somefile.php by either redirecting or showing a default image.

About the headers, that's what tells the browser what type of file it will be handling, so make sure you specify them always. For example:

#somefile.php

header('content-type: image/jpeg');  

$watermark = imagecreatefrompng('watermark.png');  
$watermark_width = imagesx($watermark);  
$watermark_height = imagesy($watermark);

$image = imagecreatetruecolor($watermark_width, $watermark_height);  
$image = imagecreatefromjpeg($_GET['src']);  //Path to the image file

$size = getimagesize($_GET['src']);          
$dest_x = $size[0] - $watermark_width - 5;  
$dest_y = $size[1] - $watermark_height - 5;

imagecopymerge($image, $watermark, $dest_x, $dest_y, 0, 0, $watermark_width, $watermark_height, 100);  
imagejpeg($image);  
imagedestroy($image);  
imagedestroy($watermark);  

So to output an image with this code on your html page, you would do the following:

<img src='somefile.php?src=filePath' />

Note: If you don't want jpg just change it to png.

More documentation about GD + PHP available here.

0

精彩评论

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