PHP 将网页转图片

如果常用微博的话可以发现有个长微博工具,可以将一段文字转成图片,然后发在微博上,比如锤子,长微博工具 www.changweibo.com

这里以 PHP 为例,使用 PHP 来对页面截图。

一个 demo

  1. error_reporting(7);

  2. define('ROOT', getcwd());

  3. define('BASEDIR', parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH));

  4. if ($_POST['text']) {

  5.    $ret  = array();

  6.    $text = $_POST['text'];

  7.    try {

  8.        $ret['imgurl'] = text2img($text, (array) $_REQUEST['config']);

  9.    }

  10.    catch (Exception $e) {

  11.        $ret['imgurl'] = print_r($e, true);

  12.    }

  13.    echo str_replace('\\/', '/', json_encode($ret));

  14.    exit(0);

  15. }

  16. function text2img($text, $options = array())

  17. {

  18.  

  19.    //http://yuncode.net/code/c_51dd01a4d547f26

  20.    $rows      = substr_count($text, "\n") + 1;

  21.    $font_path = $options['fontfile'] ? $options['fontfile'] : ROOT . '/simhei.ttf';//cp /c/Windows/Fonts/simhei.ttf .

  22.    if (!file_exists($font_path))

  23.        throw new Exception(" 找不到字体文件:$font_path  ");

  24.    $font_size       = $options['fontsize'] ? $options['fontsize'] : 12;

  25.    $padding         = $options['padding'] ? $options['padding'] : 30;

  26.    $row_plus_height = $options['row_plus_height'] ? $options['row_plus_height'] : 4;

  27.    $border          = 1;

  28.    $im_width        = 430;

  29.    $im_height       = ($row_plus_height + ($font_size * 4) / 3) * $rows + ($padding + $border) * 2;

  30.    $im              = @imagecreatetruecolor($im_width, $im_height);

  31.    if (!$im)

  32.        throw new Exception("初始化图片失败,请检查 GD 配置");

  33.    imagefilledrectangle($im, $border, $border, ($im_width - 2 * $border), ($im_height - 2 * $border), imagecolorallocate($im, 255, 255, 255));

  34.    imagettftext($im, $font_size, 0, ($border + $padding), (($font_size * 4) / 3 + $border + $padding), imagecolorallocate($im, 0, 0, 0), $font_path, $text);

  35.    $base_path      = '/files';

  36.    $base_filename  = date("Y-m-d,H-i-s") . '.png';

  37.    $short_filename = $base_path . '/' . $base_filename;

  38.    $short_url      = rtrim(BASEDIR, '/') . $short_filename;

  39.    @mkdir(ROOT . $base_path, 0777, true);

  40.    $filename = ROOT . $short_filename;

  41.    if (!imagepng($im, $filename)) {

  42.        throw new Exception("创建图片时出错。");

  43.    }

  44.    @imagedestroy($im);

  45.    return $short_url;

  46. }

  47.  

  48. ?>

  49.  

  50. <!DOCTYPE HTML><html><head>

  51. <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

  52. <title>长微博工具</title>

  53. <script type="text/javascript" src="http://lib.sinaapp.com/js/jquery/1.6.2/jquery.min.js"></script>

  54. </head>

  55. <body>

  56. <h1>长微博工具</h1>

  57. <p><textarea name="text" id="text" rows="20" cols="60"></textarea></p>

  58. <pre id="pre"></pre>

  59. <p><a target="_blank" href="" id="url"></a></p>

  60. <p><input type="button" id="format" value="格式化" /><input type="button" id="button" value="生成长微博" /> <br/><br/><br/><br/> <a href="http://changweibo.debake.com/" style="font-size:9px; color:#666; text-decoration:none">长微博</a></p>

  61. <script type="text/javascript">

  62. BIG_FONT_WIDTH = 44;

  63.  

  64. function f(v,w,c){

  65.    c = 0;

  66.    w = w || BIG_FONT_WIDTH;

  67.    return v.replace(/[\S\s]/g,function(a){

  68.        if(/[\r\n]/.test(a)) {

  69.            c = -2;

  70.            return "\r\n";

  71.        }

  72.        c += /[\x00-\xFF]/.test(a) ? 1 : 2;

  73.        if(c>=w){

  74.            c = 0;

  75.            return "\r\n"+a;

  76.        }

  77.        return a;

  78.    });

  79. }

  80. $(function(){

  81.    $("#format").click(function(){$("#text").val(f($("#text").val()));});

  82.    $("#button").click(function(){

  83.        if($("#text").val().length<1){

  84.            alert("无内容");

  85.        } else {

  86.            $.ajax({

  87.                type:"POST",

  88.                url:location.pathname,

  89.                data:"text="+$("#text").val(),

  90.                dataType:"json",

  91.                success:function(m){

  92.                    if(m.message)$("#pre").innerHTML(m.message);

  93.                    if(m.imgurl)$("#url").attr("href", m.imgurl).text(m.imgurl);

  94.                }

  95.            });

  96.        }

  97.    });

  98. });

  99. </script>

  100. </body>

  101. </html>

text2pic

  1. composer require dsgygb/text2pic

  2. touch test.php

  3. <?php

  4. require 'vendor/autoload.php';

  5.  

  6. $transform = new Text2pic\Transform('by text2pic');

  7. $result = $transform->generate("hello world");

  8. print_r($result);

  9. #中文字体路径 /c/windows/fonts/sihei.ttf

  10. $transform=new Text2pic\Transform($by,$uploadsPath,$uploadsUrl,$fontPath);

wkhtmltopdf

地址 https://wkhtmltopdf.org/downloads.html 下载后有 2 个工具 wkhtmltoimage 和 wkhtmltopdf 分别是将网页转图片和pdf 的,具体使用参考 http://blog.csdn.net/qq_14873105/article/details/51394026

  1. #生成图片 https://gist.github.com/vibbow/5702882

  2. wkhtmltoimage http://www.baidu.com/ baidu.jpg

  3. #php 调用 使用绝对路径

  4. $r=shell_exec("/user/bin/wkhtmltoimage http://www.baidu.com/ baidu.jpg");

  5. $r=shell_exec("/user/bin/wkhtmltoimage -q {$filename}.html {$filename}.jpg");

phpwkhtmltopdf

  1. composer require mikehaertl/phpwkhtmltopdf

  2. require './vendor/autoload.php';

  3. use mikehaertl\wkhtmlto\Image;

  4.  

  5. // You can pass a filename, a HTML string, an URL or an options array to the constructor

  6. $image = new Image('/path/to/page.html');

  7. $image->saveAs('/path/to/page.png');//保存

  8.  

  9. // ... or send to client for inline display

  10. $image->send();//浏览器显示

  11.  

  12. // ... or send to client as file download

  13. $image->send('page.png');//浏览器显示并下载

  14.  

  15. #另外一个库https://github.com/knplabs/snappy

  16. use Knp\Snappy\Pdf as newpdf;

  17. $snappy = new newpdf('wkhtmltopdf');

  18. header('Content-Type: application/pdf');

  19. header('Content-Disposition: attachment; filename="file.pdf"');

  20. // echo $snappy->getOutput('http://www.github.com');

  21. $snappy->generateFromHtml('<h1>Bill</h1><p>You owe me money, dude.</p>', 'bill-123.pdf');

more

  1. 小人举牌图片生成 https://github.com/jokin1999/HoldUpSign

  2. 网页保存为图片及高清截图的优化https://segmentfault.com/a/1190000011425316

  3. https://*.com/questions/5663814/how-do-i-get-wkhtmltopdf-to-execute-via-php http://www.jianshu.com/p/4d65857ffe5e

 

上一篇:验证码破解之-打码平台介绍


下一篇:Kafka Eagle安装