Use PHP + JavaScript to convert an HTML page to an image instance sharing _ javascript skills

Source: Internet
Author: User
This article mainly introduces how to use PHP + JavaScript to convert HTML elements into images. After this article, only the replaced fonts are displayed, it cannot be said that converting a static page into an image can speed up loading, but this method is more suitable for interestingXD users. 1. Preparation Elements

1) Replace the js file with the font

Js Code:

Function com_stewartspeak_replacement () {/* Dynamic Heading Generator By Stewart Rosenberger http://www.stewartspeak.com/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 must be changed to var testURL =" dynatext/loading.gif "; // the corresponding image path var doNotPrintImages = false; var printerCSS = "replacement-print.css? 1.1.9 "; var hideFlicker = false; var hideFlickerCSS =" replacement-screen.css? 1.1.9 "; var hideFlickerTimeout = 100; // here you can modify it accordingly/* recommend For basic usage, you shoshould not need to edit anything below this comment. if you need to further customize this script's abilities, make sure you'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 ('
 '); Window. flickerCheck = function () {if (! ImageLoaded) setStyleSheetState ('hide-flicker', false) ;}; setTimeout ('window. flickerCheck (); ', hideFlickerTimeout)} if (doNotPrintImages) document. write ('
 '); 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
 
  
0) for (var j = 0; j
  
   
-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
   
    
-1) ;}; break; default: checkFunction = function (e) {return e. getAttribute (attrName) ;};} currentContext = new Array; var currentContextIndex = 0; for (var k = 0; k
    
     

2) generate the PHP file for the image

<? Php/* Dynamic Heading Generator By Stewart Rosenberger http://www.stewartspeak.com/headings/ This script generates PNG images of text, written in the font/size that you specify. these PNG images are passed back to the browser. optionally, they can be cached for later use. if a cached image is found, a new image will not be generated, and the existing copy will be sent to the browser. additional documentation on PHP's image handling capabilities can be found http://www.php.net/image/ */$ Font_file = 'trebuc. ttf'; // you can make the corresponding xiuga $ font_size = 23; // you can make the corresponding changes $ font_color = '#000000'; $ background_color = '# ffff '; $ transparent_background = true; $ cache_images = true; $ cache_folder = 'cache';/* handle For basic usage, you shoshould not need to edit anything below this comment. if you need to further customize this script 'S abilities, make sure you are familiar with PHP and its image handling capabilities. required */$ mime_type = 'image/png '; $ extension = '.png'; $ send_buffer_size = 4096; // check for GD supportif (! Function_exists ('imagecreate') fatal_error ('error: Server does not support PHP image generation'); // 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 ($ background_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 cocould 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. */fun Ction get_dip ($ font, $ size) {$ test_chars = 'abcdefghijklmnopqrstuvwxyz '. 'abcdefghijklmnopqrstuvwxyz'. '123 '.'! @ # $ % ^ &*()\'"\\/;.,'~ <> [] {}- + _-= '; $ 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 is sent to the browser. if not, an error is logged, and passed back to the browser as a 500 code instead. */function fatal_error ($ message) {// send an image if (function_exists ('imagecreate') {$ width = ImageFontWidth (5) * strle N ($ message) + 10; $ height = ImageFontHeight (5) + 10; if ($ image = ImageCreate ($ width, $ height )) {$ background = ImageColorAllocate ($ image, 255,255,255); $ text_color = ImageColorAllocate ($ image, 0, 0); ImageString ($ image, 5, 5, 5, $ message, $ text_color); header ('content-type: image/png '); ImagePNG ($ image); ImageDestroy ($ image); exit ;}} // send 500 code header ("HTTP/1.0 500 Internal Server Error" ); Print ($ message); exit;}/* decode an HTML hex-code into an array of R, G, and B values. accepts these formats: (case insensitive) # ffffff, ffffff, # fff, fff */function hex_to_rgb ($ hex) {// remove '#' if (substr ($ 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_m Atch_all ('/% u ([0-9A-F] {4})/I', $ text, $ matches); if (! Empty ($ matches) for ($ I = 0; $ I
      

3) required font

Here, you need to put yourself in the same directory as the js and PHP files (you can also modify it, but the corresponding file also needs to be modified)

4) PHP GD2 Library

2. Implemented html code

<? Php // load the popup utils library // require_once 'include/popup_utils.inc.php ';?>      Professional Search Engine Optimization with PHP: Table of Contents    
Related Article

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.