By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
464,367 Members | 1,281 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 464,367 IT Pros & Developers. It's quick & easy.

Problem facing while Dynamic Image Creation to replace Font Embedding

100+
P: 245
Hey all,

I am using a PHP script which creates headings at run time in a sense at page execution. I am stuck a with a very little problem which i am sure i will have the solution from experts.

The problem is when it creates transparent PNG format image then and it pixel ate the image. e.g.

If i am using a gradient in background then it vary in color range. Now when i used that php script it generates image successfully but it pixel ate the image.

So my question how can i fix that. i am attaching the code which i am using for that and a *.jpg of screen shot for better understanding of my problem.

generate-headings.php Page
Expand|Select|Wrap|Line Numbers
  1. $font_file  = 'fonts/arial.ttf' ;
  2.     $font_size  = 20 ;
  3.     $font_color = '#ffffff' ;
  4.     $background_color = '#ffffff' ;
  5.     $transparent_background  = true ;
  6.     $cache_images = true ;
  7.     $cache_folder = 'cache' ;
  8.  
  9.     $mime_type = 'image/png' ;
  10.     $extension = '.png' ;
  11.     $send_buffer_size = 4096 ;
  12.  
  13.     $text = $_GET['text'];
  14.  
  15.     if(get_magic_quotes_gpc()){
  16.         $text = stripslashes($text) ;
  17.     }
  18.     $text = javascript_to_html($text) ;
  19.  
  20.     // look for cached copy, send if it exists
  21.     $hash = md5(basename($font_file) . $font_size . $font_color . $background_color . $transparent_background . $text) ;
  22.     $cache_filename = $cache_folder . '/' . $hash . $extension ;
  23.     if($cache_images && ($file = @fopen($cache_filename,'rb'))){
  24.         header('Content-type: ' . $mime_type) ;
  25.         while(!feof($file))
  26.             print(($buffer = fread($file,$send_buffer_size))) ;
  27.         fclose($file) ;
  28.         exit ;
  29.     }
  30.  
  31.     // check font availability
  32.     $font_found = is_readable($font_file) ;
  33.     if(!$font_found){
  34.         //fatal_error('Error: The server is missing the specified font.') ;
  35.     }
  36.  
  37.     // create image
  38.     $background_rgb = hex_to_rgb($background_color) ;
  39.     $font_rgb = hex_to_rgb($font_color) ;
  40.     $dip = get_dip($font_file,$font_size) ;
  41.     $box = @ImageTTFBBox($font_size,0,$font_file,$text) ;
  42.     $image = @ImageCreate(abs($box[2]-$box[0]),abs($box[5]-$dip)) ;
  43.     if(!$image || !$box){
  44.         fatal_error('Error: The server could not create this heading image.') ;
  45.     }
  46.  
  47.     // allocate colors and draw text
  48.     $background_color = @ImageColorAllocate($image,$background_rgb['red'],$background_rgb['green'],$background_rgb['blue']) ;
  49.     $font_color = ImageColorAllocate($image,$font_rgb['red'],$font_rgb['green'],$font_rgb['blue']) ;   
  50.     ImageTTFText($image,$font_size,0,-$box[0],abs($box[5]-$box[3])-$box[1],$font_color,$font_file,$text) ;
  51.  
  52.     // set transparency
  53.     if($transparent_background)
  54.         ImageColorTransparent($image,$background_color) ;
  55.  
  56.     header('Content-type: ' . $mime_type) ;
  57.     ImagePNG($image) ;
  58.  
  59.     // save copy of image for cache
  60.     if($cache_images){
  61.         @ImagePNG($image,$cache_filename) ;
  62.     }
  63.  
  64.     ImageDestroy($image) ;
  65.     exit ;
  66.  
  67.     /*$im = imagecreatetruecolor(300, 18);
  68.     $white = imagecolorallocate($im, 255, 255, 255);
  69.     $black = imagecolorallocate($im, 0, 0, 0);
  70.     imagefilledrectangle($im, 0, 0, imagesx($im), imagesy($im), gd_bkg());
  71.     $text = $_GET[hd];
  72.     $font = "fonts/Abduction.ttf";
  73.     imagettftext($im,14,0,0,13,$black,$font,$text);
  74.     imagepng($im);
  75.     imagedestroy($im);
  76.  
  77.     $background_rgb = hex_to_rgb($background_color) ;
  78.     $background_color = @ImageColorAllocate($image,$background_rgb['red'],*/
  79.  
  80.  
  81.     //=============================== FUNCTIONS =================
  82.     function javascript_to_html($text){
  83.         $matches = null ;
  84.         preg_match_all('/%u([0-9A-F]{4})/i',$text,$matches) ;
  85.         if(!empty($matches)) for($i=0;$i<sizeof($matches[0]);$i++)
  86.             $text = str_replace($matches[0][$i],'&#'.hexdec($matches[1][$i]).';',$text) ;
  87.         return $text ;
  88.     }
  89.     function hex_to_rgb($hex){
  90.         // remove '#'
  91.         if(substr($hex,0,1) == '#')
  92.             $hex = substr($hex,1) ;
  93.  
  94.         // expand short form ('fff') color
  95.         if(strlen($hex) == 3){
  96.             $hex = substr($hex,0,1) . substr($hex,0,1) . substr($hex,1,1) . substr($hex,1,1) . substr($hex,2,1) . substr($hex,2,1) ;
  97.         }
  98.  
  99.         if(strlen($hex) != 6)
  100.             fatal_error('Error: Invalid color "'.$hex.'"') ;
  101.  
  102.         // convert
  103.         $rgb['red'] = hexdec(substr($hex,0,2)) ;
  104.         $rgb['green'] = hexdec(substr($hex,2,2)) ;
  105.         $rgb['blue'] = hexdec(substr($hex,4,2)) ;
  106.  
  107.         return $rgb ;
  108.     }
  109.     function get_dip($font,$size){
  110.         $test_chars = 'abcdefghijklmnopqrstuvwxyz' .
  111.                       'ABCDEFGHIJKLMNOPQRSTUVWXYZ' .
  112.                       '1234567890' .
  113.                       '!@#$%^&*()\'"\\/;.,`~<>[]{}-+_-=' ;
  114.         $box = @ImageTTFBBox($size,0,$font,$test_chars) ;
  115.         return $box[3] ;
  116.     }
  117.  
Javascript File which used to replace text with images

Expand|Select|Wrap|Line Numbers
  1. function com_stewartspeak_replacement() {
  2. /*
  3.     Dynamic Heading Generator
  4.     By Stewart Rosenberger
  5.     http://www.stewartspeak.com/headings/
  6.  
  7.     This script searches through a web page for specific or general elements
  8.     and replaces them with dynamically generated images, in conjunction with
  9.     a server-side script.
  10. */
  11.  
  12.  
  13. replaceSelector("h2","generate-headings.php",true);
  14. var testURL = "http://bytes.com/images/test.png" ;
  15.  
  16. var doNotPrintImages = false;
  17. var printerCSS = "includes/replacement-print.css";
  18.  
  19. var hideFlicker = false;
  20. var hideFlickerCSS = "includes/replacement-screen.css";
  21. var hideFlickerTimeout = 1000;
  22.  
  23.  
  24.  
  25.  
  26. /* ---------------------------------------------------------------------------
  27.     For basic usage, you should not need to edit anything below this comment.
  28.     If you need to further customize this script's abilities, make sure
  29.     you're familiar with Javascript. And grab a soda or something.
  30. */
  31.  
  32. var items;
  33. var imageLoaded = false;
  34. var documentLoaded = false;
  35.  
  36. function replaceSelector(selector,url,wordwrap){
  37.     if(typeof items == "undefined")
  38.         items = new Array();
  39.  
  40.     items[items.length] = {selector: selector, url: url, wordwrap: wordwrap};
  41. }
  42.  
  43. if(hideFlicker)
  44. {        
  45.     document.write('<link id="hide-flicker" rel="stylesheet" media="screen" href="' + hideFlickerCSS + '" />');        
  46.     window.flickerCheck = function()
  47.     {
  48.         if(!imageLoaded)
  49.             setStyleSheetState('hide-flicker',false);
  50.     };
  51.     setTimeout('window.flickerCheck();',hideFlickerTimeout)
  52. }
  53.  
  54. if(doNotPrintImages)
  55.     document.write('<link id="print-text" rel="stylesheet" media="print" href="' + printerCSS + '" />');
  56.  
  57. var test = new Image();
  58. test.onload = function() { imageLoaded = true; if(documentLoaded) replacement(); };
  59. test.src = testURL + "?date=" + (new Date()).getTime();
  60. alert(test.src);
  61. addLoadHandler(function(){ documentLoaded = true; if(imageLoaded) replacement(); });
  62.  
  63.  
  64. function documentLoad()
  65. {
  66.     documentLoaded = true;
  67.     if(imageLoaded)
  68.         replacement();
  69. }
  70.  
  71. function replacement()
  72. {
  73.     for(var i=0;i<items.length;i++)
  74.     {
  75.         var elements = getElementsBySelector(items[i].selector);
  76.         if(elements.length > 0) for(var j=0;j<elements.length;j++)
  77.         {
  78.             if(!elements[j])
  79.                 continue ;
  80.  
  81.             var text = extractText(elements[j]);
  82.             while(elements[j].hasChildNodes())
  83.                 elements[j].removeChild(elements[j].firstChild);
  84.  
  85.             var tokens = items[i].wordwrap ? text.split(' ') : [text] ;
  86.             for(var k=0;k<tokens.length;k++)
  87.             {
  88.                 var url = items[i].url + "?text="+escape(tokens[k]+' ')+"&selector="+escape(items[i].selector);
  89.                 var image = document.createElement("img");
  90.                 image.className = "replacement";
  91.                 image.alt = tokens[k] ;
  92.                 image.src = url;
  93.                 elements[j].appendChild(image);
  94.             }
  95.  
  96.             if(doNotPrintImages)
  97.             {
  98.                 var span = document.createElement("span");
  99.                 span.style.display = 'none';
  100.                 span.className = "print-text";
  101.                 span.appendChild(document.createTextNode(text));
  102.                 elements[j].appendChild(span);
  103.             }
  104.         }
  105.     }
  106.  
  107.     if(hideFlicker)
  108.         setStyleSheetState('hide-flicker',false);
  109. }
  110.  
  111. function addLoadHandler(handler)
  112. {
  113.     if(window.addEventListener)
  114.     {
  115.         window.addEventListener("load",handler,false);
  116.     }
  117.     else if(window.attachEvent)
  118.     {
  119.         window.attachEvent("onload",handler);
  120.     }
  121.     else if(window.onload)
  122.     {
  123.         var oldHandler = window.onload;
  124.         window.onload = function piggyback()
  125.         {
  126.             oldHandler();
  127.             handler();
  128.         };
  129.     }
  130.     else
  131.     {
  132.         window.onload = handler;
  133.     }
  134. }
  135.  
  136. function setStyleSheetState(id,enabled) 
  137. {
  138.     var sheet = document.getElementById(id);
  139.     if(sheet)
  140.         sheet.disabled = (!enabled);
  141. }
  142.  
  143. function extractText(element)
  144. {
  145.     if(typeof element == "string")
  146.         return element;
  147.     else if(typeof element == "undefined")
  148.         return element;
  149.     else if(element.innerText)
  150.         return element.innerText;
  151.  
  152.     var text = "";
  153.     var kids = element.childNodes;
  154.     for(var i=0;i<kids.length;i++)
  155.     {
  156.         if(kids[i].nodeType == 1)
  157.         text += extractText(kids[i]);
  158.         else if(kids[i].nodeType == 3)
  159.         text += kids[i].nodeValue;
  160.     }
  161.  
  162.     return text;
  163. }
  164.  
  165. /*
  166.     Finds elements on page that match a given CSS selector rule. Some
  167.     complicated rules are not compatible.
  168.     Based on Simon Willison's excellent "getElementsBySelector" function.
  169.     Original code (with comments and description):
  170.         http://simon.incutio.com/archive/2003/03/25/getElementsBySelector
  171. */
  172. function getElementsBySelector(selector)
  173. {
  174.     var tokens = selector.split(' ');
  175.     var currentContext = new Array(document);
  176.     for(var i=0;i<tokens.length;i++)
  177.     {
  178.         token = tokens[i].replace(/^\s+/,'').replace(/\s+$/,'');
  179.         if(token.indexOf('#') > -1)
  180.         {
  181.             var bits = token.split('#');
  182.             var tagName = bits[0];
  183.             var id = bits[1];
  184.             var element = document.getElementById(id);
  185.             if(tagName && element.nodeName.toLowerCase() != tagName)
  186.                 return new Array();
  187.             currentContext = new Array(element);
  188.             continue;
  189.         }
  190.  
  191.         if(token.indexOf('.') > -1)
  192.         {
  193.             var bits = token.split('.');
  194.             var tagName = bits[0];
  195.             var className = bits[1];
  196.             if(!tagName)
  197.                 tagName = '*';
  198.  
  199.             var found = new Array;
  200.             var foundCount = 0;
  201.             for(var h=0;h<currentContext.length;h++)
  202.             {
  203.                 var elements;
  204.                 if(tagName == '*')
  205.                     elements = currentContext[h].all ? currentContext[h].all : currentContext[h].getElementsByTagName('*');
  206.                 else
  207.                     elements = currentContext[h].getElementsByTagName(tagName);
  208.  
  209.                 for(var j=0;j<elements.length;j++)
  210.                     found[foundCount++] = elements[j];
  211.             }
  212.  
  213.             currentContext = new Array;
  214.             var currentContextIndex = 0;
  215.             for(var k=0;k<found.length;k++)
  216.             {
  217.                 if(found[k].className && found[k].className.match(new RegExp('\\b'+className+'\\b')))
  218.                     currentContext[currentContextIndex++] = found[k];
  219.             }
  220.  
  221.             continue;
  222.         }
  223.  
  224.         if(token.match(/^(\w*)\[(\w+)([=~\|\^\$\*]?)=?"?([^\]"]*)"?\]$/))
  225.         {
  226.             var tagName = RegExp.$1;
  227.             var attrName = RegExp.$2;
  228.             var attrOperator = RegExp.$3;
  229.             var attrValue = RegExp.$4;
  230.             if(!tagName)
  231.                 tagName = '*';
  232.  
  233.             var found = new Array;
  234.             var foundCount = 0;
  235.             for(var h=0;h<currentContext.length;h++)
  236.             {
  237.                 var elements;
  238.                 if(tagName == '*')
  239.                     elements = currentContext[h].all ? currentContext[h].all : currentContext[h].getElementsByTagName('*');
  240.                 else
  241.                     elements = currentContext[h].getElementsByTagName(tagName);
  242.  
  243.                 for(var j=0;j<elements.length;j++)
  244.                     found[foundCount++] = elements[j];
  245.             }
  246.  
  247.             currentContext = new Array;
  248.             var currentContextIndex = 0;
  249.             var checkFunction;
  250.             switch(attrOperator)
  251.             {
  252.                 case '=':
  253.                     checkFunction = function(e) { return (e.getAttribute(attrName) == attrValue); };
  254.                     break;
  255.                 case '~':
  256.                     checkFunction = function(e) { return (e.getAttribute(attrName).match(new RegExp('\\b'+attrValue+'\\b'))); };
  257.                     break;
  258.                 case '|':
  259.                     checkFunction = function(e) { return (e.getAttribute(attrName).match(new RegExp('^'+attrValue+'-?'))); };
  260.                     break;
  261.                 case '^':
  262.                     checkFunction = function(e) { return (e.getAttribute(attrName).indexOf(attrValue) == 0); };
  263.                     break;
  264.                 case '$':
  265.                     checkFunction = function(e) { return (e.getAttribute(attrName).lastIndexOf(attrValue) == e.getAttribute(attrName).length - attrValue.length); };
  266.                     break;
  267.                 case '*':
  268.                     checkFunction = function(e) { return (e.getAttribute(attrName).indexOf(attrValue) > -1); };
  269.                     break;
  270.                 default :
  271.                     checkFunction = function(e) { return e.getAttribute(attrName); };
  272.             }
  273.  
  274.             currentContext = new Array;
  275.             var currentContextIndex = 0;
  276.             for(var k=0;k<found.length;k++)
  277.             {
  278.                 if(checkFunction(found[k]))
  279.                     currentContext[currentContextIndex++] = found[k];
  280.             }
  281.  
  282.             continue;
  283.         }
  284.  
  285.         tagName = token;
  286.         var found = new Array;
  287.         var foundCount = 0;
  288.         for(var h=0;h<currentContext.length;h++)
  289.         {
  290.             var elements = currentContext[h].getElementsByTagName(tagName);
  291.             for(var j=0;j<elements.length; j++)
  292.                 found[foundCount++] = elements[j];
  293.         }
  294.  
  295.         currentContext = found;
  296.     }
  297.  
  298.     return currentContext;
  299. }
  300.  
  301.  
  302. }// end of scope, execute code
  303. if(document.createElement && document.getElementsByTagName && !navigator.userAgent.match(/opera\/?6/i))
  304.     com_stewartspeak_replacement();
  305.  
  306.  
Attached Images
File Type: jpg error.jpg (5.9 KB, 197 views)
Apr 2 '09 #1
Share this Question
Share on Google+
1 Reply

hsriat
Expert 100+
P: 1,654
I could not see any "pixel ate" happening. Even it does happen, I believe it would be a error in your algorithm.

PS: I am inferring "pixel ate" as what happens to the videos being shown on the national TV channels when there's some inappropriate content/scene.
Apr 10 '09 #2

Post your reply

Sign in to post your reply or Sign up for a free account.