473,721 Members | 2,259 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Problem facing while Dynamic Image Creation to replace Font Embedding

245 New Member
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, 211 views)
Apr 2 '09 #1
1 3390
hsriat
1,654 Recognized Expert Top Contributor
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

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

Similar topics

5
1797
by: Jim Buzbee | last post by:
I have a subroutine that inserts image objects into a page for me. It works fine except for one thing. My mouseover settings don't appear to take. i.e. I see nothing at all when I move the mouse cursor over the image. If I replace the object creation code with a plain document.write, it works. : // this works as expected document.write("<img src='marker12.gif' \ id='1' \
5
4392
by: Tompa | last post by:
Hi, I would like to create images on the fly as a response to an http request. I can do this with PIL like this (file create_gif.py): from PIL import Image, ImageDraw print 'Status: 200 OK' print 'Content-type: text/html' print print '<HTML><HEAD><TITLE>Python Dynamic Image Creation Test</TITLE></HEAD>'
2
8949
by: Lyn | last post by:
I am trying to embed a picture into a Bound Object Frame (Me!Photograph) with the following code which is based on MS article http://support.microsoft.com/?id=158941: strPathname = "C:\photo.bmp" Me!Photograph.Class = "Paint.Picture" Me!Photograph.OLETypeAllowed = acOLEEmbedded Me!Photograph.SourceDoc = strPathname Me!Photograph.Action = acOLECreateEmbed
2
1556
by: hemant.singh | last post by:
I am stuck with strange JS issue My product gives user to show some images(which track mouseover) on page by embedding script like <script src=http://domain.com/GetDynamicJS?domagic=1> </script> Now user is embedding more than of the above and when user mouse over's the image output of first1 than function getting called is script loaded in last ... thus error, as that script don't have the relevant
7
3789
by: Ben | last post by:
Hi We are looking for a component that offers that offers the below for Tiff files: Image clean-up (deskew, despeckle) Printing capabilities from VB The ability to add text to image, e.g. time / date Nice to have:
0
3502
by: sjickells | last post by:
Hi I am having a problem using asp:TextBox's in a transparent table. I have a background image on the page and a table in the middle of the page. I have set the background colour of the table to white the used CSS to set the opacity to 90 so that you can see the background image through the table. The problem I am having is with the textboxes in the transparent
0
1292
by: boeledi | last post by:
I'm new in GDI programming and I am facing the following problem. I try to dynamically create "thumbnail"-like images (JPEG) in which I need to draw text. This works fine, except that the text is always a little bit "blurred". Here is the code, could someone give me some help? Thanks in advance, Didier Public Shared Function AppropriateFont(ByVal g As Graphics, ByVal
2
3151
by: swethak | last post by:
Hi, I am getting the problem the problem with google map in Internet Explorer. This map worked fine in mozilla . When i opened the same map in Internet Explorer i am getting the error message as in alert box as " Internet Explorer cannot open the Internet site http://google.citycarrentals.com.au/viewalllocations.php . Operation aborted". It is working in Mozilla . Here i mentioned my code . I am facing this problem several...
6
4447
by: Sajeena | last post by:
<?php // starting word $text = "My Text"; //Start MS Word $Word = new COM("word.application") or die("Failure: Word did not start"); echo("WORD has started."); //Formating the Font $Word->Visible=0;
0
8840
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8730
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
9367
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
9064
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
8007
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
6669
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5981
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4753
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3189
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.