使用PHP+JavaScript将HTML页面转换为图片的实例分享

 更新时间:2016年4月19日 10:00  点击:6787

1,准备要素

1)替换字体的js文件

js代码:

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);//前两个参数需要修改
var testURL = "dynatext/loading.gif" ;//修改为对应的图片路径
 
var doNotPrintImages = false;
var printerCSS = "replacement-print.css";
 
var hideFlicker = false;
var hideFlickerCSS = "replacement-screen.css";
var hideFlickerTimeout = 100;//这里可以做相应的修改

/* ---------------------------------------------------------------------------
  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'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 are 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(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) == attrValue); };
          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 code
if(document.createElement && document.getElementsByTagName && !navigator.userAgent.match(/opera\/?6/i))
  com_stewartspeak_replacement();

2)生成图片的php文件

<?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 at http://www.php.net/image/  
*/

$font_file = 'trebuc.ttf' ;//可以做相应的xiuga
$font_size = 23 ;//可以做相应的修改
$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
  are familiar with PHP and its image handling capabilities.
 ---------------------------------------------------------------------------
*/
 
$mime_type = 'image/png' ;
$extension = '.png' ;
$send_buffer_size = 4096 ;
 
// check for GD support
if(!function_exists('ImageCreate'))
  fatal_error('Error: Server does not support PHP image generation') ;
 
// clean up text
if(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 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 transparency
if($transparent_background)
  ImageColorTransparent($image,$background_color) ;
 
header('Content-type: ' . $mime_type) ;
ImagePNG($image) ;
 
// save copy of image for cache
if($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 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) * 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 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_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],
              '&#'.hexdec($matches[1][$i]).';',$text) ;
 
  return $text ;
}
 
?>

3)需要的字体

这里将需要的自己放在与js和php文件同在的一个目录下(也可以修改,但是对应文件也要修改)

4)PHP的GD2库

2,实现的html代码

<?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">
<html>
  <head>
    <title>
      Professional Search Engine Optimization with PHP: Table of Contents
    </title>
    <script type="text/javascript" language="javascript" src="dynatext/replacement.js"></script>
  </head>
  <body onload="window.resizeTo(800,600);" onresize='setTimeout("window.resizeTo(800,600);", 100)'>
    <h1>
      Professional Search Engine Optimization with PHP: Table of Contents
    </h1>
    <?php
      //display popup navigation only when visitor comes from a SERP
      // display_navigation();
      //display_popup_navigation();
    ?>
    <ol>
      <li>You: Programmer and Search Engine Marketer</li>
      <li>A Primer in Basic SEO</li>
      <li>Provocative SE-Friendly URLs</li>
      <li>Content Relocation and HTTP Status Codes</li>
      <li>Duplicate Content</li>
      <li>SE-Friendly HTML and JavaScript</li>
      <li>Web Syndication and Social Bookmarking</li>
      <li>Black Hat SEO</li>
      <li>Sitemaps</li>
      <li>Link Bait</li>
      <li>IP Cloaking, Geo-Targeting, and IP Delivery</li>
      <li>Foreign Language SEO</li>
      <li>Coping with Technical Issues</li>
      <li>Site Clinic: So You Have a Web Site?</li>
      <li>WordPress: Creating a SE-Friendly Weblog?</li>
      <li>Introduction to Regular Expression</li>
    </ol>
  </body>
</html>

3,使用效果前后对比
使用前

2016418174755219.png (1160×394)

使用后

2016418174816337.png (961×401)

[!--infotagslink--]

相关文章

  • 使用PHP+JavaScript将HTML页面转换为图片的实例分享

    这篇文章主要介绍了使用PHP+JavaScript将HTML元素转换为图片的实例分享,文后结果的截图只能体现出替换的字体,也不能说将静态页面转为图片可以加快加载,只是这种做法比较interesting XD需要的朋友可以参考下...2016-04-19
  • C#和JavaScript实现交互的方法

    最近做一个小项目不可避免的需要前端脚本与后台进行交互。由于是在asp.net中实现,故问题演化成asp.net中jiavascript与后台c#如何进行交互。...2020-06-25
  • 关于JavaScript中name的意义冲突示例介绍

    在昨天的《Javascript权威指南》学习笔记之十:ECMAScript 5 增强的对象模型一文中,对于一段代码的调试出现了一个奇怪现象,现将源代码贴在下面: 复制代码 代码如下: <script type="text/javascript"> function Person(){}...2014-05-31
  • javascript自定义的addClass()方法

    复制代码 代码如下: //element:需要添加新样式的元素,value:新的样式 function addClass(element, value ){ if (!element.className){ element.className = value; }else { newClassName = element.className; newClas...2014-05-31
  • JavaScript中的this关键字使用方法总结

    在javascritp中,不一定只有对象方法的上下文中才有this, 全局函数调用和其他的几种不同的上下文中也有this指代。 它可以是全局对象、当前对象或者任意对象,这完全取决于函数的调用方式。JavaScript 中函数的调用有以下...2015-03-15
  • JavaScript中逗号运算符介绍及使用示例

    有一道js面试题,题目是这样的:下列代码的执行结果是什么,为什么? 复制代码 代码如下: var i, j, k; for (i=0, j=0; i<10, j<6; i++, j++) { k = i+j; } document.write(k); 答案是显示10,这道题主要考察JavaScript的逗...2015-03-15
  • javascript的事件触发器介绍的实现

    事件触发器从字面意思上可以很好的理解,就是用来触发事件的,但是有些没有用过的朋友可能就会迷惑了,事件不是通常都由用户在页面上的实际操作来触发的吗?这个观点不完全正确,因为有些事件必须由程序来实现,如自定义事件,jQue...2014-06-07
  • 详解javascript数组去重问题

    首先,我想到的是另建一个结果数组,用来存储原始数组中不重复的数据。遍历原始数组依次跟结果数组中的元素进行比较,检测是否重复。于是乎,我写出了如下代码A: Array.prototype.clearRepetitionA = function(){ var resul...2015-11-08
  • ActiveX控件与Javascript之间的交互示例

    1、ActiveX向Javascript传参 复制代码 代码如下: <script language="javascript" for="objectname" event="fun1(arg)"> fun2(arg); </script> objectname为ActiveX控件名,通过<object>标签里的id属性设定,如下; 复制...2014-06-07
  • Javascript类型转换的规则实例解析

    这篇文章主要介绍了Javascript类型转换的规则实例解析,涉及到javascript类型转换相关知识,对本文感兴趣的朋友一起学习吧...2016-02-27
  • JavaScript获取浏览器信息的方法

    Window有navigator对象让我们得知浏览器的全部信息.我们可以利用一系列的API函数得知浏览器的信息.JavaScript代码如下:function message(){ txt = "<p>浏览器代码名: " + navigator.appCodeName + "</p>";txt+= "<p>...2015-11-24
  • 详解JavaScript操作HTML DOM的基本方式

    通过 HTML DOM,可访问 JavaScript HTML 文档的所有元素。 HTML DOM (文档对象模型) 当网页被加载时,浏览器会创建页面的文档对象模型(Document Object Model)。 HTML DOM 模型被构造为对象的树: 通过可编程的对象模型,Java...2015-10-23
  • 跟我学习javascript的最新标准ES6

    虽然ES6都还没真正发布,但已经有用ES6重写的程序了,各种关于ES789的提议已经开始了,这你敢信。潮流不是我等大众所能追赶的。潮流虽然太快,但我们不停下学习的步伐,就不会被潮流丢下的,下面来领略下ES6中新特性,一堵新生代JS...2015-11-24
  • javascript设计模式之解释器模式详解

    神马是“解释器模式”?先翻开《GOF》看看Definition:给定一个语言,定义它的文法的一种表示,并定义一个解释器,这个解释器使用该表示来解释语言中的句子。在开篇之前还是要科普几个概念: 抽象语法树: 解释器模式并未解释如...2014-06-07
  • JavaScript操作URL的相关内容集锦

    ---恢复内容开始---1.location.href.....(1)self.loction.href="http://www.cnblogs.com/url" window.location.href="http://www.cnblogs.com/url" 以上两个用法相同均为在当前页面打开URL页面 (2)this.locati...2015-10-30
  • javascript实现tab切换的四种方法

    tab切换在网页中很常见,故最近总结了4种实现方法。 首先,写出tab的框架,加上最简单的样式,代码如下: <!DOCTYPE html> <html> <head><meta http-equiv="Content-Type" content="text/html; charset=utf-8" /><style> *{ pa...2015-11-08
  • 基于JavaScript如何实现私有成员的语法特征及私有成员的实现方式

    前言在面向对象的编程范式中,封装都是必不可少的一个概念,而在诸如 Java,C++等传统的面向对象的语言中, 私有成员是实现封装的一个重要途径。但在 JavaScript 中,确没有在语法特性上对私有成员提供支持, 这也使得开发人员使...2015-10-30
  • 利用JS实现点击按钮后图片自动切换的简单方法

    下面小编就为大家带来一篇利用JS实现点击按钮后图片自动切换的简单方法。小编觉得挺不错的,现在就分享给大家,也给大家做个参考。一起跟随小编过来看看吧...2016-10-25
  • javascript实现数独解法

    生生把写过的java版改成javascript版,第一次写,很不专业,见谅。唉,我是有多闲。复制代码 代码如下: var Sudoku = { init: function (str) { this.blank = []; this.fixed = []; this.cell =...2015-03-15
  • javascript中slice(),splice(),split(),substring(),substr()使用方法

    1.slice();Array和String对象都有在Array中 slice(i,[j])i为开始截取的索引值,负数代表从末尾算起的索引值,-1为倒数第一个元素 j为结束的索引值,缺省时则获取从i到末尾的所有元素参数返回: 返回索引值从i到j的数组,原数组...2015-03-15