Image processing and output using GD in php

女生的网名这么多〃 提交于 2019-12-12 10:07: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 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 and 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?


回答1:


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.



来源:https://stackoverflow.com/questions/2010742/image-processing-and-output-using-gd-in-php

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