Convert an HTML page to a picture using Php+javascript

Source: Internet
Author: User
This article mainly describes the use of Php+javascript to convert HTML elements to a picture of the instance share, the results can only reflect the replacement of the font, or the static page to the picture can be accelerated loading, but this practice compared to interesting xd needs of friends can refer to the next

1, prepare the essentials

1) Replace the font JS file

JS Code:

function Com_stewartspeak_replacement () {/* Dynamic Heading Generator by Stewart Rosenberger http://www.stewartspeak.co  M/headings/this script searches through a Web page for specific or general elements and replaces them with dynamically Generated images, in conjunction with a server-side script.*/replaceselector ("H1", "dynatext/heading.php", true);// The first two parameters need to be modified var testurl = "Dynatext/loading.gif";//modified to the corresponding picture path var donotprintimages = False;var Printercss = "REPLACEMENT-PR Int.css "; var hideflicker = False;var hideflickercss = "Replacement-screen.css"; var hideflickertimeout = 100;//You can make the appropriate changes here/*------ ---------------------------------------------------------------------for basic usage, you should not need to edit Anyth  ing below this comment. If you need to further customize this script's abilities, make sure your ' re familiar with Javascript. And grab a soda or something.*/var items;var imageloaded = False;var documentloaded = false; function Replaceselector (selector,url,wordwrap) {  if (typeof items = = "undefined") items = new Array (); Items[items.length] = {selector:selector, url:url, wordwrap:wordwrap};} if (hideflicker) {document.write (' <link id= "Hide-flicker" rel= "stylesheet" media= "screen" href= "' + hideflickercss      + '/> ');  Window.flickercheck = function () {if (!imageloaded) setstylesheetstate (' Hide-flicker ', false);  }; SetTimeout (' Window.flickercheck (); ', Hideflickertimeout)} if (donotprintimages) document.write (' <link id= ' Print-text "rel=" stylesheet "media=" print "href=" ' + printercss + ' "/> '); var test = new Image (), test.onload = function () {imageloaded = true; if (documentloaded) replacement ();}; TEST.SRC = Testurl + "? date=" + (new Date ()). GetTime ();  Addloadhandler (function () {documentloaded = true; if (imageloaded) replacement ();});  function Documentload () {documentloaded = true; if (imageloaded) replacement ();} function replacement () {for (Var i=0;i<items.length;i++) {var elements = GetelementsbyselEctor (Items[i].selector);           if (Elements.length > 0) for (Var j=0;j<elements.length;j++) {if (!elements[j]) continue;      var text = Extracttext (elements[j]);       while (Elements[j].haschildnodes ()) Elements[j].removechild (Elements[j].firstchild); var tokens = Items[i].wordwrap?      Text.split ("): [text]; for (Var k=0;k<tokens.length;k++) {var url = items[i].url + "? text=" +escape (tokens[k]+ ") +" &selector= "        +escape (Items[i].selector);        var image = document.createelement ("img");        Image.classname = "Replacement";        Image.alt = Tokens[k];        image.src = URL;      Elements[j].appendchild (image);        } if (donotprintimages) {var span = document.createelement ("span");        Span.style.display = ' None ';        Span.classname = "Print-text";        Span.appendchild (document.createTextNode (text));      Elements[j].appendchild (span); }}} if (Hideflicker) setstylesheetstate(' Hide-flicker ', false);}  function Addloadhandler (handler) {if (Window.addeventlistener) {Window.addeventlistener ("load", handler,false);  } else if (window.attachevent) {window.attachevent ("onload", Handler);    } else if (window.onload) {var oldhandler = window.onload;      Window.onload = function piggyback () {Oldhandler ();    Handler ();  };  } else {window.onload = handler;  }} function Setstylesheetstate (id,enabled) {var sheet = document.getElementById (ID); if (sheet) sheet.disabled = (!enabled);}  function Extracttext (Element) {if (typeof element = = "string") return element;  else if (typeof element = = "undefined") return element;   else if (element.innertext) return element.innertext;  var text = "";  var kids = element.childnodes;    for (Var i=0;i<kids.length;i++) {if (Kids[i].nodetype = = 1) text + = Extracttext (Kids[i]);  else if (Kids[i].nodetype = = 3) text + = Kids[i].nodevalue; } return text;} /* Finds elements on page thaT match a given CSS selector rule.  Some complicated rules is not compatible.  Based on Simon Willison ' s excellent "getelementsbyselector" function. Original code (with comments and description): http://simon.incutio.com/archive/2003/03/25/getelementsbyselector*/  function Getelementsbyselector (selector) {var tokens = Selector.split (');  var currentcontext = new Array (document);    for (Var i=0;i<tokens.length;i++) {token = Tokens[i].replace (/^\s+/, "). Replace (/\s+$/,");      if (Token.indexof (' # ') >-1) {var bits = token.split (' # ');      var tagName = bits[0];      var id = bits[1];      var element = document.getElementById (ID);      if (TagName && element.nodeName.toLowerCase ()! = TagName) return new Array ();      CurrentContext = new Array (element);    Continue      } if (Token.indexof ('. ') >-1) {var bits = token.split ('. ');      var tagName = bits[0];      var className = bits[1];       if (!tagname) tagName = ' * '; Var Found = new Array;      var foundcount = 0;        for (Var h=0;h<currentcontext.length;h++) {var elements; if (TagName = = ' * ') elements = Currentcontext[h].all?        Currentcontext[h].all:currentcontext[h].getelementsbytagname (' * ');         else elements = Currentcontext[h].getelementsbytagname (tagName);      for (Var j=0;j<elements.length;j++) found[foundcount++] = Elements[j];      } currentcontext = new Array;      var currentcontextindex = 0; for (Var k=0;k<found.length;k++) {if (Found[k].classname && Found[k].classname.match (The New RegExp (' \\b      ' +classname+ ' \\b '))) currentcontext[currentcontextindex++] = found[k];    } continue; } if (Token.match (/^ (\w*) \[(\w+) ([=~\|\^\$\*]?) =?"?      ([^\] "]*)"? \]$/) {var tagName = regexp.$1;      var attrname = regexp.$2;      var attroperator = regexp.$3;      var attrValue = regexp.$4;       if (!tagname) tagName = ' * '; var found = new Array;      var foundcount = 0;        for (Var h=0;h<currentcontext.length;h++) {var elements; if (TagName = = ' * ') elements = Currentcontext[h].all?        Currentcontext[h].all:currentcontext[h].getelementsbytagname (' * ');         else elements = Currentcontext[h].getelementsbytagname (tagName);      for (Var j=0;j<elements.length;j++) found[foundcount++] = Elements[j];      } currentcontext = new Array;      var currentcontextindex = 0;      var checkfunction; Switch (attroperator) {case ' = ': Checkfunction = function (e) {return (E.getattribute (attrname) = = Trvalue);          };        Break Case ' ~ ': checkfunction = function (e) {return (E.getattribute (attrname). Match (New RegExp (' \\b ' +attrvalue+ ' \\b ')) );          };        Break  Case ' | ': checkfunction = function (e) {return (E.getattribute (attrname). Match (new RegExp (' ^ ' +attrvalue+ '-? ')));          };        Break    Case ' ^ ':      Checkfunction = function (e) {return (E.getattribute (attrname). IndexOf (attrValue) = = 0);};        Break Case ' $ ': checkfunction = function (e) {return (E.getattribute (attrname). LastIndexOf (attrValue) = = E.getattribute (attrname). Length-attrvalue.length);          };        Break          Case ' * ': checkfunction = function (e) {return (E.getattribute (attrname). IndexOf (AttrValue) >-1);};        Break      Default:checkfunction = function (e) {return e.getattribute (attrname);};      } currentcontext = new Array;      var currentcontextindex = 0; for (Var k=0;k<found.length;k++) {if (Checkfunction (Found[k])) currentcontext[currentcontextindex++      ] = Found[k];    } continue;    } tagName = token;    var found = new Array;    var foundcount = 0;      for (Var h=0;h<currentcontext.length;h++) {var elements = Currentcontext[h].getelementsbytagname (tagName); for (Var J=0;j<elements.lengTh    J + +) found[foundcount++] = Elements[j];  } CurrentContext = found;  } return currentcontext;} }//end of Scope, execute Codeif (document.createelement && document.getelementsbytagname &&! Navigator.userAgent.match (/opera\/?6/i)) com_stewartspeak_replacement ();

2) Create a picture of the PHP file

<?php/* Dynamic Heading Generator by Stewart rosenberger http://www.stewartspeak.com/headings/This script Gener Ates PNG images of text, written in the font/size so you specify. These PNG images is passed back to the browser.   Optionally, they can be cached for later use.   If A cached image is found, a new image won't be generated, and the existing copy would be sent to the browser. Additional documentation on PHP ' s image handling capabilities can is found at http://www.php.net/image/*/$font _file = ' Trebuc.ttf ';//can do the corresponding xiuga$font_size = 23;//can make corresponding changes $font_color = ' #000000 '; $background _color = ' #ffffff '; $ Transparent_background = true; $cache _images = true; $cache _folder = ' cache ';/*---------------------------------------  ------------------------------------for basic usage, you should not need to edit anything below this comment. If you need to further customize this script ' s abilities, make sure you is familiar with PHP and its image handling CAPA BilitieS.---------------------------------------------------------------------------*/$mime _type = ' image/png '; $ Extension = '. png '; $send _buffer_size = 4096; Check for GD supportif (!function_exists (' Imagecreate's)) Fatal_error (' Error:server does not support PHP image Generati On ');   Clean up textif (empty ($_get[' text ")) Fatal_error (' Error:no text specified. '); $text = $_get[' text '], if (GET_MAGIC_QUOTES_GPC ()) $text = Stripslashes ($text), $text = javascript_to_html ($text);      Look for cached copy, send if it exists$hash = MD5 (basename ($font _file). $font _size. $font _color. $background _color. $transparent _background. $text); $cache _filename = $cache _folder. '/' . $hash.   $extension, if ($cache _images && ($file = @fopen ($cache _filename, ' RB ')) {header (' Content-type: '. $mime _type);  while (!feof ($file)) print ($buffer = Fread ($file, $send _buffer_size));  Fclose ($file); Exit;} Check font availability$font_found = is_readable ($font _file); if (! $font _found) {fatal_error (' error:the server is missing the specified font. ');}//Create Image$background_rgb = Hex_to_rgb ($back Ground_color); $font _rgb = Hex_to_rgb ($font _color); $dip = Get_dip ($font _file, $font _size); $box = @ImageTTFBBox ($font _ size,0, $font _file, $text), $image = @ImageCreate (ABS ($box [2]-$box [0]), ABS ($box [5]-$dip)); if (! $image | |! $box) {Fatal_ Error (' Error:the Server could not create this heading image. ');} Allocate colors and draw Text$background_color = @ImageColorAllocate ($image, $background _rgb[' Red '], $background _rgb [' Green '], $background _rgb[' Blue '), $font _color = Imagecolorallocate ($image, $font _rgb[' red '), $font _rgb[' green '],$  font_rgb[' Blue '); Imagettftext ($image, $font _size,0,-$box [0],abs ($box [5]-$box [3])-$box [1], $font _color, $font _file, $text); Set Transparencyif ($transparent _background) imagecolortransparent ($image, $background _color); Header (' Content-type: '. $mime _type); Imagepng ($image); Save copy of image for Cacheif ($cache _images) {@ImagePNG ($image, $cache _filename);}  Imagedestroy ($image); exit; /* Try to determine the ' dip ' (pixels dropped below baseline) of this font for this size.*/function Get_dip ($font, $size)         {$test _chars = ' abcdefghijklmnopqrstuvwxyz '.         ' ABCDEFGHIJKLMNOPQRSTUVWXYZ '.         ' 1234567890 '.  '!@#$%^&* () \ ' "\\/;., ' ~<>[]{}-+_-= ';  $box = @ImageTTFBBox ($size, 0, $font, $test _chars);  return $box [3];}   /* Attempt to create an image containing the error message given. If this works, the image was sent to the browser. If not, an error was logged, and passed back to the browser as a code instead.*/function fatal_error ($message) {//SE    nd an image if (function_exists (' imagecreate ')) {$width = Imagefontwidth (5) * strlen ($message) + 10;    $height = Imagefontheight (5) + 10;      if ($image = Imagecreate ($width, $height)) {$background = Imagecolorallocate ($image, 255,255,255);      $text _color = imagecolorallocate ($image, 0,0,0); Imagestring ($image, 5,5,5, $mesSage, $text _color);      Header (' content-type:image/png ');      Imagepng ($image);      Imagedestroy ($image);    Exit;  }}//Send the Code header ("http/1.0 Internal Server Error");  Print ($message);  Exit;}  /* Decode an HTML hex-code to an array of r,g, and B values. Accepts these formats: (case insensitive) #ffffff, FFFFFF, #fff, FFF */function Hex_to_rgb ($hex) {//Remove ' # ' if (sub   STR ($hex, 0,1) = = ' # ') $hex = substr ($hex, 1);        Expand Short Form (' FFF ') color if (strlen ($hex) = = 3) {$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);   } if (strlen ($hex)! = 6) fatal_error (' Error:invalid color '. $hex. ' ");  Convert $rgb [' red '] = Hexdec (substr ($hex, 0,2));  $rgb [' green '] = Hexdec (substr ($hex, 2,2));   $rgb [' blue '] = Hexdec (substr ($hex, 4,2));  return $RGB;} /* Convert embedded, JavaScript Unicode characters into embedded HTML entities. (e.g. '%U2018 ' = ').  Returns the converted String.*/function javascript_to_html ($text) {$matches = null;  Preg_match_all ('/%u ([0-9a-f]{4})/I ', $text, $matches); if (!empty ($matches)) for ($i =0; $i <sizeof ($matches [0]), $i + +) $text = Str_replace ($matches [0][$i], ". Hexd   EC ($matches [1][$i]). '; ', $text); return $text;} ?>

3) Required Fonts

Here will need to be placed in the same directory with the JS and PHP files (can also be modified, but also to modify the corresponding file)

4) PHP GD2 Library

2, implementing the HTML code

<?php//load the popup utils library//require_once ' include/popup_utils.inc.php ';? ><! DOCTYPE HTML PUBLIC "-//w3c//dtd XHTML 1.1//en" "Http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd" >

3, use the effect before and after comparison
Before use

After use

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.