html转image--通过casperjs在服务器端实现

casperjs可以理解为phantomjs的二次开发,所以安装使用casperjs之前必须要先安装phantomjs。

(一),Install

(1) http://phantomjs.org/download.html
download:phantomjs-2.1.1-linux-x86_64.tar.bz2
tar -jxvf /home/developer/casper/phantomjs-2.1.1-linux-x86_64.tar.bz2

ln -sf /home/developer/casper/phantomjs/bin/phantomjs /usr/bin/phantomjs
phantomjs --version
=>2.1.1

(2)http://casperjs.org/
download: casperjs-1.1.3.zip
解压
ln -sf /home/developer/casper/casperjs/bin/casperjs /usr/bin/casperjs
casperjs --version
=>1.1.2


(二)casperjs文件准备

/**
casperjs /path/to/capture.js page_url filename.png [selector]
第一个参数是网页的网址
第二个截取屏幕后的存储的文件的名
第三个参数是选择器,比如'.main','.content','#data-list'之类的(支持CSS3选择器)。此参数是可选的,如果指定了,就只会截取该选择器命中的区域。否则,就截取整个网页。
 */
var casper = require('casper').create({
    verbose: true,
    logLevel: 'debug',
    viewportSize:{width:1920,height:1200}
});

var args = casper.cli.args;
var url = args[0];
var filename = args[1];
var selector = args[2];

casper.start(url);
var callbackFun = function() {
    var args = [filename];
    var method = 'capture';
    if (selector) {
        args.push(selector);
        method = 'captureSelector';
    }
    this[method].apply(this, args);
}

var nextStep ='then';
var nextStepArgs= [callbackFun];
if(selector){
    nextStep = 'waitForSelector';
    nextStepArgs.unshift(selector);
    nextStepArgs.push(function(){this.echo('Timeout Error!!!')});
    nextStepArgs.push(10000);
}

casper[nextStep].apply(casper,nextStepArgs);

casper.run(function() {
    this.echo('Done.').exit();
});


(三)terminal测试

casperjs /home/developer/casper/test.js http://www.baidu.com /home/developer/casper/baidu.png


==>至此,服务器端可以截取html页面,生成图片。


(四)服务器端执行cmd

以php语言为例

(1)Web服务器端

   public function screenShotAndUpload(){

            /*
             * casperjs /home/developer/casper/test.js http://xxxxx/product/sizeTable/form?encode_prd_dat_siz_tbl=xxxxxxxx /home/developer/casper/test.png '#size-table-real'
             */

            $url = getAdminHost()."/product/sizeTable/form?encode_prd_dat_siz_tbl=".$encode_prd_dat_siz_tbl;
            $target_file_path = '/home/developer/casper/test.png';
            $selector = "'#size-table-real'";

            $cmd = "casperjs /home/developer/casper/test.js {$url} {$target_file_path} {$selector}";
            ob_start();
            @system($cmd);
            ob_end_clean();


            $cfile = new CURLFile($target_file_path,'image/png','test.png');
            list($curl_getinfo, $result) = $this->requestFileApi('/product.php', array(
                'up' => $cfile
            ));

            $result = json_decode($result, TRUE);

            ...........................

            获取文件服务器返回的url应答,进行db保存

  }


    private function requestFileApi($file_serverse_url, $params) {
        $ch = curl_init();
        curl_setopt ($ch, CURLOPT_URL, $file_serverse_url);
        curl_setopt ($ch, CURLOPT_HEADER, FALSE);
        curl_setopt ($ch, CURLOPT_POST, TRUE);
        curl_setopt ($ch, CURLOPT_SAFE_UPLOAD, TRUE);
        curl_setopt ($ch, CURLOPT_POSTFIELDS, $params );
        curl_setopt    ($ch, CURLOPT_RETURNTRANSFER, TRUE);
        $response = curl_exec($ch);
        $curl_getinfo = curl_getinfo($ch);
        curl_close($ch);
        return array($curl_getinfo, $response);
    }


(2)文件服务器端

<?php
    require_once('xxx.php');
    require_once('yyy.php');

    $response = array();
    $response['error']        = TRUE;
    $response['msg']        = 'File Upload Error';
    $response['original']    = '';
    $response['thumbnail']    = '';
    $response['preview']    = '';

    $file_name = hash('sha256', uniqid());
    $file_name_temp = str_split($file_name, 2);
    $sub_path = $file_name_temp[0];
    $y = date('Y');
    $md = date('md');

    $d = 'dafault';
    $path_uri = getFileHost().'/files/'.$d.'/'.$y.'/'.$md.'/'.$sub_path.'/';
    $path =  rtrim(getFilesPath(), '/').'/files/'.$d.'/'.$y.'/'.$md.'/'.$sub_path.'/';
    makeDir($path);

    if (!isset($_FILES["up"]) || !is_uploaded_file($_FILES["up"]["tmp_name"]) || $_FILES["up"]["error"] != 0)
    {
        header("HTTP/1.1 500 Fail uploaded images.");
        $response['error']        = TRUE;
        $response['msg']        = 'Fail uploaded images.';
        echo json_encode($response);
        exit;
    }

    $parse_file_arr    = explode('.', strtolower(trim($_FILES['up']['name'])));
    $file_ext = array_pop( $parse_file_arr );
    $file_path = "{$path}{$file_name}.{$file_ext}";

    if (move_uploaded_file($_FILES['up']['tmp_name'], $file_path))
    {
        $response['original'] = "{$path_uri}{$file_name}.{$file_ext}";

        if(isset($_POST['thumbsize']) || isset($_POST['presize']) ) {
            $thumb = new Imagick($file_path);

            if(isset($_POST['thumbsize'])) {
                $thumbsize = explode('x', urldecode($_POST['thumbsize']));
                if(count($thumbsize) == 2)
                {
                    $thumb->thumbnailImage((int)$thumbsize[0], (int)$thumbsize[1]) ;
                    $thumb->writeImages(getUploadThumbnailPath($file_path), true);
                    $response['thumbnail'] = getUploadThumbnailPath($response['original']);
                }
            }

            if(isset($_POST['presize'])) {
                $presize = explode('x', urldecode($_POST['presize']));
                if(count($presize) == 2)
                {
                    $thumb->thumbnailImage((int)$presize[0], (int)$presize[1]);
                    $thumb->writeImages(getUploadPreviewPath($file_path), true);
                    $response['preview'] = getUploadPreviewPath($response['original']);
                }
            }

            $thumb->clear();
            $thumb->destroy();
        }
        $response['error']        = FALSE;
        $response['msg']        = "success";
    }
    else
    {
        header("HTTP/1.1 500 Fail uploaded images.");
        $response['error']        = TRUE;
        $response['msg']        = 'Fail uploaded images.';
    }

    echo json_encode($response);
?>

 

注意:

这种在服务器端截取图片的方式实现简单,但是有2个缺点.

(1)在服务器端处理,服务器压力大

(2)截取到服务器端的临时图片需要及时删除,如果web使用的云服务器,那么这种方式实现的话,不可靠。可以在客户端通过html2canvas实现。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值