首頁 >後端開發 >php教程 >使用PHP+JavaScript將HTML頁面轉換為圖片

使用PHP+JavaScript將HTML頁面轉換為圖片

不言
不言原創
2018-06-02 10:01:484145瀏覽

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

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(&#39;<link id="hide-flicker" rel="stylesheet" media="screen" href="&#39; + hideFlickerCSS + &#39;" />&#39;);    
  window.flickerCheck = function()
  {
    if(!imageLoaded)
      setStyleSheetState(&#39;hide-flicker&#39;,false);
  };
  setTimeout(&#39;window.flickerCheck();&#39;,hideFlickerTimeout)
}
 
if(doNotPrintImages)
  document.write(&#39;<link id="print-text" rel="stylesheet" media="print" href="&#39; + printerCSS + &#39;" />&#39;);
 
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(&#39; &#39;) : [text] ;
      for(var k=0;k<tokens.length;k++)
      {
        var url = items[i].url + "?text="+escape(tokens[k]+&#39; &#39;)+"&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 = &#39;none&#39;;
        span.className = "print-text";
        span.appendChild(document.createTextNode(text));
        elements[j].appendChild(span);
      }
    }
  }
 
  if(hideFlicker)
    setStyleSheetState(&#39;hide-flicker&#39;,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&#39;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(&#39; &#39;);
  var currentContext = new Array(document);
  for(var i=0;i<tokens.length;i++)
  {
    token = tokens[i].replace(/^\s+/,&#39;&#39;).replace(/\s+$/,&#39;&#39;);
    if(token.indexOf(&#39;#&#39;) > -1)
    {
      var bits = token.split(&#39;#&#39;);
      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(&#39;.&#39;) > -1)
    {
      var bits = token.split(&#39;.&#39;);
      var tagName = bits[0];
      var className = bits[1];
      if(!tagName)
        tagName = &#39;*&#39;;
 
      var found = new Array;
      var foundCount = 0;
      for(var h=0;h<currentContext.length;h++)
      {
        var elements;
        if(tagName == &#39;*&#39;)
          elements = currentContext[h].all ? currentContext[h].all : currentContext[h].getElementsByTagName(&#39;*&#39;);
        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(&#39;\\b&#39;+className+&#39;\\b&#39;)))
          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 = &#39;*&#39;;
 
      var found = new Array;
      var foundCount = 0;
      for(var h=0;h<currentContext.length;h++)
      {
        var elements;
        if(tagName == &#39;*&#39;)
          elements = currentContext[h].all ? currentContext[h].all : currentContext[h].getElementsByTagName(&#39;*&#39;);
        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 &#39;=&#39;:
          checkFunction = function(e) { return (e.getAttribute(attrName) == attrValue); };
          break;
        case &#39;~&#39;:
          checkFunction = function(e) { return (e.getAttribute(attrName).match(new RegExp(&#39;\\b&#39;+attrValue+&#39;\\b&#39;))); };
          break;
        case &#39;|&#39;:
          checkFunction = function(e) { return (e.getAttribute(attrName).match(new RegExp(&#39;^&#39;+attrValue+&#39;-?&#39;))); };
          break;
        case &#39;^&#39;:
          checkFunction = function(e) { return (e.getAttribute(attrName).indexOf(attrValue) == 0); };
          break;
        case &#39;$&#39;:
          checkFunction = function(e) { return (e.getAttribute(attrName).lastIndexOf(attrValue) == e.getAttribute(attrName).length - attrValue.length); };
          break;
        case &#39;*&#39;:
          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&#39;s image handling capabilities can
  be found at http://www.php.net/image/  
*/

$font_file = &#39;trebuc.ttf&#39; ;//可以做相应的xiuga
$font_size = 23 ;//可以做相应的修改
$font_color = &#39;#000000&#39; ;
$background_color = &#39;#ffffff&#39; ;
$transparent_background = true ;
$cache_images = true ;
$cache_folder = &#39;cache&#39; ;

/*
 ---------------------------------------------------------------------------
  For basic usage, you should not need to edit anything below this comment.
  If you need to further customize this script&#39;s abilities, make sure you
  are familiar with PHP and its image handling capabilities.
 ---------------------------------------------------------------------------
*/
 
$mime_type = &#39;image/png&#39; ;
$extension = &#39;.png&#39; ;
$send_buffer_size = 4096 ;
 
// check for GD support
if(!function_exists(&#39;ImageCreate&#39;))
  fatal_error(&#39;Error: Server does not support PHP image generation&#39;) ;
 
// clean up text
if(empty($_GET[&#39;text&#39;]))
  fatal_error(&#39;Error: No text specified.&#39;) ;
   
$text = $_GET[&#39;text&#39;] ;
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 . &#39;/&#39; . $hash . $extension ;
if($cache_images && ($file = @fopen($cache_filename,&#39;rb&#39;)))
{
  header(&#39;Content-type: &#39; . $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(&#39;Error: The server is missing the specified font.&#39;) ;
}
 
// 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(&#39;Error: The server could not create this heading image.&#39;) ;
}
 
// allocate colors and draw text
$background_color = @ImageColorAllocate($image,$background_rgb[&#39;red&#39;],
  $background_rgb[&#39;green&#39;],$background_rgb[&#39;blue&#39;]) ;
$font_color = ImageColorAllocate($image,$font_rgb[&#39;red&#39;],
  $font_rgb[&#39;green&#39;],$font_rgb[&#39;blue&#39;]) ;  
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(&#39;Content-type: &#39; . $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 = &#39;abcdefghijklmnopqrstuvwxyz&#39; .
         &#39;ABCDEFGHIJKLMNOPQRSTUVWXYZ&#39; .
         &#39;1234567890&#39; .
         &#39;!@#$%^&*()\&#39;"\\/;.,`~<>[]{}-+_-=&#39; ;
  $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(&#39;ImageCreate&#39;))
  {
    $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(&#39;Content-type: image/png&#39;) ;
      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 &#39;#&#39;
  if(substr($hex,0,1) == &#39;#&#39;)
    $hex = substr($hex,1) ;
 
  // expand short form (&#39;fff&#39;) 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(&#39;Error: Invalid color "&#39;.$hex.&#39;"&#39;) ;
 
  // convert
  $rgb[&#39;red&#39;] = hexdec(substr($hex,0,2)) ;
  $rgb[&#39;green&#39;] = hexdec(substr($hex,2,2)) ;
  $rgb[&#39;blue&#39;] = hexdec(substr($hex,4,2)) ;
 
  return $rgb ;
}
 
 
/*
  convert embedded, javascript unicode characters into embedded HTML
  entities. (e.g. &#39;%u2018&#39; => &#39;‘&#39;). returns the converted string.
*/
function javascript_to_html($text)
{
  $matches = null ;
  preg_match_all(&#39;/%u([0-9A-F]{4})/i&#39;,$text,$matches) ;
  if(!empty($matches)) for($i=0;$i<sizeof($matches[0]);$i++)
    $text = str_replace($matches[0][$i],
              &#39;&#39;.hexdec($matches[1][$i]).&#39;;&#39;,$text) ;
 
  return $text ;
}
 
?>

3)需要的字体

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

4)PHP的GD2库

2,实现的html代码

<?php
//load the popup utils library
//require_once &#39;include/popup_utils.inc.php&#39;;
?>
<!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=&#39;setTimeout("window.resizeTo(800,600);", 100)&#39;>
    <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)

相关推荐:

PHP+JavaScript实现无刷新上传图片的方法

PHP+JavaScript实现Cookie的读写、交互操作方法详解

以上是使用PHP+JavaScript將HTML頁面轉換為圖片的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn