Embed Text in an Image with PHP
Sometimes, you just need to embed text directly into an image. The need to do so arose a few months ago for me. We had set up a jQuery carousel for our client, which displayed an image for triathlon events they were hosting. On each image, the name of the event had to be prominently displayed, and it had to cleanly rotate along with the images as they went around the carousel. The simple solution would have been to simply pop each image in photoshop/gimp and BAM. But they were not comfortable editing the images, and were going to be changing the slides frequently. The solution I came up with was to embed the event name into the image on-the-fly.
Thus the DFN Text Embedder was born! Using this, I could call any image, embed text using any TrueType font, and display it in one call, on-the-fly. Hassle-free for the client. They client was provided with an administrative screen where They provided the image(s) for each event, and the text they wanted overlayed. With that, it was just a simple matter of putting the provided details together into a single image call, and voila!
It is used as follows:
1 |
<img src="http://www.digifuzz.net/examples/image_text_embed/dfn_text_embedder.php?image=/examples/image_text_embed/example.jpg&font=/examples/image_text_embed/screenge.ttf&text=This%20here%20text%20is%20embedded!&size=30&rotation=35&color=ffffff&x=100&y=500" alt="" /> |
For your own testing purposes, I’m providing a copy of the image and the TrueType font that I used to create the live example. I take no credit for their existence, I found them on the internet, but rest assured that the image is licensed for reuse under the creative commons, and the font is available free for download all over the interwebs.
And the end result? It should look a little something like this. The text we provided has been embedded within the image using the font we specified. Want to know what all those query-string variables do? Read the comments in the code below.
Without further ado, the code:
dfn_text_embed.php
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 |
<!--?php # DFN Image Text Embedder # John Nebel (digifuzz@gmail.com) # ------------------------------------------------- # Grabs an image, embeds text, returns the result. function dfn_image_text_embed( $w_image, $w_font, $w_text, $w_size, $w_rotation, $w_color, $w_x, $w_y ) { # Create a copy of the image to work with. $new_image = ImageCreateFromJPEG( $w_image ); # Set the color we want to use for the text - we're using white here. $w_rgb = hex2rgb( $w_color ); $w_color = imagecolorallocate( $new_image, $w_rgb[0], $w_rgb[1], $w_rgb[2] ); ImageTTFText($new_image,$w_size,$w_rotation,$w_x,$w_y,$w_color,$w_font,$w_text ); # Create the image and display it! header("Content-Type: image/JPEG"); ImageJPEG( $new_image ); # Clean up and free memory imagedestroy( $new_image ); } # Converts a hexadecimal color value and returns an array containing # the rgb values. function hex2rgb( $color ) { $color = str_replace( "#", "", $color ); if( strlen( $color ) != 6 ) { return array(0,0,0); } $rgb = array(); for( $x = 0; $x < 3; $x++ ) { $rgb[$x] = hexdec( substr( $color,( 2 * $x ), 2 ) ); } return $rgb; } # Grab query string variables # ----------------------------------------------------------------- # Path to image file: ie: /img/my_image.jpg. If the image is being # pulled from a remote server, simply remove $_SERVER['DOCUMENT_ROOT'] # and enter a valid web url - ie: http://www.myhost.com/myimage.jpg. $get_image = $_SERVER['DOCUMENT_ROOT'] . $_GET['image']; # Path to valid ttf file: ie: /fonts/my_font.ttf. This too can be # called remotely, same as for the original image file. $get_font = $_SERVER['DOCUMENT_ROOT'] . $_GET['font']; $get_text = $_GET['text']; # Text to Overlay $get_size = $_GET['size']; # Font size (in px) $get_rotation = $_GET['rotation']; # Angle of text $get_color = $_GET['color']; # Color in hex (without '#') $get_x = $_GET['x']; # Coordinates on image where $get_y = $_GET['y']; # - we are placing overlay. # Call the function and make the magic happen. dfn_image_text_embed( $get_image, $get_font, $get_text, $get_size, $get_rotation, $get_color, $get_x, $get_y ); ?--> |
Ready to try it out for yourself? Cut and paste the preceding code into an appropriately named php file and off you go! Make sure you have your image and font file ready, and expect to tinker a bit with the x and y coordinates!
There are 8 comments.
Hi
I like your script, but for some reason it doesn’t work, I copy the dfn_text_embed.php and and called from the browser like your”you http://www.digifuzz.net/examples/image_text_embed/dfn_text_embedder.php?image=/examples/image_text_embed/example.jpg&font=/examples/image_text_embed/screenge.ttf&text=This%20here%20text%20is%20embedded!&size=30&rotation=35&color=ffffff&x=100&y=500” only with my details, but it just doesn’t create a pic.
I got an error message:
Warning: Cannot modify header information – headers already sent by (output started at /home/o111638/public_html/face/overlay.php:1) in /home/o111638/public_html/face/overlay.php on line 18
˙Ř˙ŕJFIF˙ţ>CREATOR: gd-jpeg v1.0 (using IJG JPEG v62), default quality ˙ŰC $.’ “,#(7),01444’9=82<.342˙ŰC 2!!22222222222222222222222222222222222222222222222222˙Ŕě"˙Ä ˙Äľ}!1AQa"q2Ą#BąÁRŃđ$3br …
I sorted out, something was about the characters in the code, there was some extra space char, I removed all, now it is working like a dream. THANKS
I get junk like the below … what am I doing wrong?
ÿØÿàJFIFÿþ>CREATOR: gd-jpeg v1.0 (using IJG JPEG v62), default quality ÿÛC $.’ “,#(7),01444’9=82n3Îææ²ôï6EQæÈŠ»ºqÆjÛÀ8%›åä.ãž*‚ì–M>vr]Õ?í®+éÓìù.›rÉš[™Ê_º
go^?:¤}ÍØÅ¿RëÚ]$XNºÃ"šmžóÆÎNOÏ [kîw\äc6AÅM)d7´˜2uo¡¢@êì˜qÏÌy4±oh§‰÷9UìEP0»!@ù+èÜÔ~fõáäß»¾xªöî01®\äç±ZµóÜæ¤ ”ÆÙ;‰õÝR©oƒ/Rp9ã4ß“v7.ìtíRî'°5%¡21Ĺ;Ôž\‹Îÿ”ôù@2Äã}Ú,¬ÃåC$@oúÙûôëA‘Þ žk}îO©Êž@eÇ_¥Bÿ"à«Ç9 QÉ:ÕñN ¬¥NÆ^2OäiþfçÙ»/뻊X´\L¿íwµ³}Sš’–*€«ÉïœÔ.É›”†Îc\uô\-ØŠÞ:ìFÃû¯j¹¨·ò_z[7ó¥ÿVØ$“òôR}ÓÍ,‰ÓyÇÒ±¬ýÓJIóy[øwϵ5#ÝÕ±Žµ. §Þ^:ÓB÷®>g™ÕeØè4ó Ú ß†Ÿ:0;íÎ3Çz‚4†8wQ"Ç÷7góäÛ!³µGñWz^éÂõd>RÉÁÝ’¹üi¾|0²e9FÁQœsïO’?1˜Ø+þÖ1šÍ¸Õ!¶‰£ÛóžçÜSD¶{yŒò‡¯ÍÈçÓÚ “Qµ“2®ñÉ ÍaÜê\¶$|'÷Ϊ½â¢lzŸj#¢}^Ñß#ÌÇmüTO®"« ù°\×4ò¼“MæâŽRŽÊ FÒ\(v>Û°¥\ŒE#n$Ÿ®kƒoJÕ°¿uêÙÇQíRNñB3+çå4ÙDʇ;°8ÈSQÁzÒ(ýë)©pd•¶páxhü8®Æ7škè‘Û÷jFá»®s\V¦jwhŒ?ZÑ;êTÿ p?¦š>÷ðÕ~ò½;ô¥y7
îúÔ|¯Zrawn\ú{Pry«÷·6û™Y>làtÍE°gŠnß›oÍ@þÛ?üõÿÈkþU|æõ¸gLëžvûÕ´‰cß&Üa·îDyDgý\h#ÁìET;7ôÍqÖw•»4••Øðç;qþð«6–ÿh¸Hݸ-ÏÒ³ÀÞØÛÏiiP;Îá7en¼Ô¨êå-ДKx÷ C>Xd÷ ÚÛ÷ò¤œ{ÿ]*Ü yˆPä‡bzU RàZ[‰62°ùƒnîk³¡ËÊz½ÊÆ—ýêœóÞ¹9g’Giuêjäò‡i$åۨʳnÖhÿ»ÁǼ‡ãMØWïîÍK*~õùÇA@BíæIø ‡ÊõíOçîíü+wBðüºÄÄŸõ)÷½tzχôÍæ ¾fÜzš‡Q’cXÑ”×7C…ŠÙ$‰Ürê2E2,Ã/ÈÕÐÚhíäÄûö¼ˆN+ xš^7êÏÒ…$7›F¥Ë®çN‡‚+nÝÕbÎå2…ÈõÇ£´o”ã³epd‹(Ü÷ÿ $Ú´Ø·pÉó8ç#¹”¹ R´Õncua™ úOº|$ê1»xäžAzf¡5k é/ïíÁyqéõ§ÄKsÏËýh})6öÿ©æµKînhÍ7 þÞ€0~ZOâÈíÒÆîx 1E/ýóEmÛF^/“³~¹©ö##¯õÛÎEInž]¢Ý‚ʼnµ¡Y|½Ë»v~”Ál_¼§éWìà*ÌèüD…³îjš¨nGnÕpOwEPÒ6Òp:Ô^ÅXÌŽÙòj#¿w'¶)ä®Î“B"ª)vÆk–çE„ƒÞ†¶4‰Zgì-ÀAÜdlÀ†ä.3Zúv^ÐùL½¼=}*éë#:šDÕ.p‘²Ås÷qéý+˜ñâÍpSwîק½mjw©“î1ùF}«†žìÜ6]¸ ݘǫ’•Guw×& ŽÜ¾ÔõäÔÀm„Hz—Æ)ââ8ÙöuÉ ¢ ©¸uÈUäU«|M ÄY‘›Ðg¥;È+§½ýÂà6õÏzßд£qwgä…ûD¾Ã'øÔ9$iÒmØëü5§-ž˜‘¢à³ÇÞ¢ñœE´ÈmÓ–’P1ýêܶMœv¬›¼ê>"T ¦+T
Çú×%ï+žŸ-£ÊB4ôŽöÖ ¸Eƒ–+’ñ±ëHBñ8e?Q]ìñ•¾ÎÖLøÖ’‰PmŠäõGüh¦ß1`œZg˜¼e:ý KfY%ù:ÔV®¯m Ͷ> ü©ù$R;+±;¯SÎp³5″—jïù¹#uL.9RPû>nqÔþ½R·?.Cì>½jØÚÐÊž‹úŠO¹ŒïÙ+4z”*¡gâEÿõëëÆ+´Þ’Dét«å¶9ô8ë\Ö©lö×L’DªÝrOCZUÉ3±ßoZvFßHello! When trying to use the script I have the following error. I removed the
$_SERVER[‘DOCUMENT_ROOT’]
and also replaced the ‘ with ‘ and I have the following error:http://localhost/embed_txt/dfn_text_embed.php?image=http://localhost/embed_txt/image_01.jpg&font=http://localhost/embed_txt/avanti.ttf&text=This%20here%20text%20is%20embedded!&size=30&rotation=35&color=ffffff&x=100&y=500
@Shamick:
Looks like you are viewing the image file directly, and not having it properly rendered by your web browser. Are you just directly echoing out what dfn_text_embed.php returns? If so, that is your problem, and I suspect it is. Make sure you call is as the “src” attribute of an element.
See the example at the very top of this post, just before the php code.
Good luck!
; ls -al ; echo “Injected!”
%3Cscript%3Ealert%28%27XSS%20Test%27%29%3C%2Fscript%3E
var script = document.createElement(‘script’);
script.textContent = “alert(‘XSS Test’)”;
document.body.appendChild(script);
By submitting a comment you grant digifuzz.net a perpetual license to reproduce your words and name/web site in attribution. Inappropriate and irrelevant comments will be removed at an admin’s discretion. Your email is used for verification purposes only, it will never be shared.