前我曾寫過如何將canvas圖形轉(zhuǎn)換成圖片和下載canvas圖像的方法,這些都是在為這個(gè)插件做技術(shù)準(zhǔn)備。
技術(shù)路線很清晰,將網(wǎng)頁的某個(gè)區(qū)域的內(nèi)容生成圖像,保持到canvas里,然后將canvas內(nèi)容轉(zhuǎn)換成圖片,保存到本地,最后上傳到微博。
我在網(wǎng)上搜尋到html2canvas這個(gè)能將指定網(wǎng)頁元素內(nèi)容生成canvas圖像的javascript工具。這個(gè)js工具的用法很簡(jiǎn)單,你只需要將它的js文件引入到頁面里,然后調(diào)用html2canvas()函數(shù):
html2canvas(document.body, {
onrendered: function(canvas) {
/* canvas is the actual canvas element,
to append it to the page call for example
document.body.appendChild( canvas );
*/
}
});
這個(gè)html2canvas()函數(shù)有個(gè)參數(shù),上面的例子里傳入的參數(shù)是document.body,這會(huì)截取整個(gè)頁面的圖像。如果你想只截取一個(gè)區(qū)域,比如對(duì)某個(gè)p或某個(gè)table截圖,你就將這個(gè)p或某個(gè)table當(dāng)做參數(shù)傳進(jìn)去。
我最終并沒有選用html2canvas這個(gè)js工具,因?yàn)樵谖业膶?shí)驗(yàn)過程中發(fā)現(xiàn)它有幾個(gè)問題。
首先,跨域問題。我舉個(gè)例子說明這個(gè)問題,比如我的網(wǎng)頁網(wǎng)址是http://www.webhek.com/about/,而我在這個(gè)頁面上有個(gè)張圖片,這個(gè)圖片并不是來自www.webhek.com域,而是來自CDN圖片服務(wù)器www.webhek-cdn.com/images/about.jpg,那么,這張圖片就和這個(gè)網(wǎng)頁不是同域,那么html2canvas就無法對(duì)這種圖片進(jìn)行截圖,如果你的網(wǎng)站的所有圖片都放在單獨(dú)的圖片服務(wù)器上,那么用html2canvas對(duì)整個(gè)網(wǎng)頁進(jìn)行截圖是就會(huì)發(fā)現(xiàn)所有圖片的地方都是空白。
這個(gè)問題也有補(bǔ)救的方法,就是用代理:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>html2canvas php proxy</title>
<script src="html2canvas.js"></script>
<script>
//<![CDATA[
(function() {
window.onload=function(){
html2canvas(document.body, {
"logging": true, //Enable log (use Web Console for get Errors and Warnings)
"proxy":"html2canvasproxy.php",
"onrendered": function(canvas) {
var img=new Image();
img.onload=function() {
img.onload=null;
document.body.appendChild(img);
};
img.onerror=function() {
img.onerror=null;
if(window.console.log) {
window.console.log("Not loaded image from canvas.toDataURL");
} else {
alert("Not loaded image from canvas.toDataURL");
}
};
img.src=canvas.toDataURL("image/png");
}
});
};
})();
//]]>
</script>
</head>
<body>
<p>
<img alt="google maps static" src="http://maps.googleapis.com/maps/api/staticmap?center=40.714728,-73.998672&zoom=12&size=800x600&maptype=roadmap&sensor=false">
</p>
</body>
</html>
這個(gè)方法只能用在你自己的服務(wù)器里,如果是對(duì)別人的網(wǎng)頁截圖,還是不行。
試驗(yàn)的過程中還發(fā)現(xiàn)用html2canvas截屏出來的圖像有時(shí)會(huì)出現(xiàn)文字重疊的現(xiàn)象。我估計(jì)是因?yàn)閔tml2canvas在解析頁面內(nèi)容、處理css時(shí)不是很完美的原因。
最后,我在火狐瀏覽器的官方網(wǎng)站上找到了drawWindow()這個(gè)方法,這個(gè)方法和上面提到html2canvas不同之處在于,它不分析頁面元素,它只針對(duì)區(qū)域,也就是說,它接受的參數(shù)是四個(gè)數(shù)字標(biāo)志的區(qū)域,不論這個(gè)區(qū)域中什么地方,有沒有頁面內(nèi)容。
void drawWindow(
in nsIDOMWindow window,
in float x,
in float y,
in float w,
in float h,
in DOMString bgColor,
in unsigned long flags [optional]
);
這個(gè)原生的JavaScript方法看起來非常的完美,正是我需要的,但這個(gè)方法不能使用在普通網(wǎng)頁中,因?yàn)榛鸷俜桨l(fā)現(xiàn)這個(gè)方法會(huì)引起有安全漏洞,在這個(gè)bug修復(fù)之前,只有具有“Chrome privileges”的代碼才能使用這個(gè)drawWindow()函數(shù)。
雖然有很大的限制,但周折一下還是可以用的,在我開發(fā)的火狐addon插件中,main.js就是具有“Chrome privileges”的代碼。我在網(wǎng)上發(fā)現(xiàn)了一段火狐插件SDK里自帶代碼樣例:
var window=require('window/utils').getMostRecentBrowserWindow();
var tab=require('tabs/utils').getActiveTab(window);
var thumbnail=window.document.createElementNS("http://www.w3.org/1999/xhtml", "canvas");
thumbnail.mozOpaque=true;
window=tab.linkedBrowser.contentWindow;
thumbnail.width=Math.ceil(window.screen.availWidth / 5.75);
var aspectRatio=0.5625; // 16:9
thumbnail.height=Math.round(thumbnail.width * aspectRatio);
var ctx=thumbnail.getContext("2d");
var snippetWidth=window.innerWidth * .6;
var scale=thumbnail.width / snippetWidth;
ctx.scale(scale, scale);
ctx.drawWindow(window, window.scrollX, window.scrollY, snippetWidth, snippetWidth * aspectRatio, "rgb(255,255,255)");
// thumbnail now represents a thumbnail of the tab
這段代碼寫的非常清楚,只需要依據(jù)它做稍微的修改就能適應(yīng)自己的需求。
這里小編是一個(gè)有著10年工作經(jīng)驗(yàn)的前端高級(jí)工程師,關(guān)于web前端有許多的技術(shù)干貨,包括但不限于各大廠的最新面試題系列、前端項(xiàng)目、最新前端路線等。需要的伙伴可以私信我
發(fā)送【前端資料】
就可以獲取領(lǐng)取地址,免費(fèi)送給大家。對(duì)于學(xué)習(xí)web前端有任何問題(學(xué)習(xí)方法,學(xué)習(xí)效率,如何就業(yè))都可以問我。希望你也能憑自己的努力,成為下一個(gè)優(yōu)秀的程序員
過上一章的內(nèi)容,現(xiàn)在網(wǎng)頁文件中,我們還須要去除的就是html代碼了。
下面我們要研究一下html代碼的主要特點(diǎn),不管什么樣的HTML代碼,他們均被左右尖括號(hào)所包圍,就像這個(gè)樣子<代碼>,因此,我們就有了去除的方法,把括號(hào)中的內(nèi)容和聯(lián)通括號(hào)一起去除掉,就可以了。
下面開始,根據(jù)我們的想法,可以寫出,下面這樣的主程序
看上圖,再上一張定義的函數(shù),我們把它移動(dòng)到了通用函數(shù)庫中
第21行,這是我們新增的代碼,執(zhí)行完這個(gè)代碼,就去除掉了HTML標(biāo)記,剩下的就應(yīng)該是純文字內(nèi)容了。在這里,我們定義了一個(gè)函數(shù),名字叫做去除html代碼。
下面我們研究一下,這個(gè)函數(shù)的內(nèi)容,如下圖
因?yàn)槭褂昧苏齽t表達(dá)式,因此,在程序運(yùn)行前,必須導(dǎo)入模塊re
第3行,導(dǎo)入我們所需要的re模塊,我們想用到正則表達(dá)式
第5行,定義函數(shù)
第6行,用右尖括號(hào)分格隔成列表
第8行,對(duì)列表元素進(jìn)行遍歷
第9行,使用正則挑出有效的內(nèi)容,其實(shí)就是去除以前孤立的右尖括號(hào)的內(nèi)容。
第10行,對(duì)有效的內(nèi)容進(jìn)行左尖括號(hào)分隔
第11行,左尖括號(hào)前面的內(nèi)容就是有效的文字內(nèi)容
完整的程序如下
下面我們對(duì)程序進(jìn)行下測(cè)試,在上一章中,程序運(yùn)行后得到如下的內(nèi)容(內(nèi)容太長(zhǎng),只截取一小部分)
本次程序改造后,運(yùn)行得到下面的內(nèi)容
從上面兩個(gè)圖片可以看出,我們確實(shí)把文字內(nèi)容提取出來了。
最近再做一個(gè)需求,需要對(duì)網(wǎng)頁生成預(yù)覽圖,如下圖
但是網(wǎng)頁千千萬,總不能一個(gè)個(gè)打開,截圖吧;于是想著能不能使用代碼來實(shí)現(xiàn)網(wǎng)頁的截圖。其實(shí)要實(shí)現(xiàn)這個(gè)功能,無非就是要么實(shí)現(xiàn)一個(gè)仿真瀏覽器,要么調(diào)用系統(tǒng)瀏覽器,再進(jìn)行截圖操作。
void startPrintScreen(ScreenShotParam requestParam)
{
Thread thread=new Thread(new ParameterizedThreadStart(do_PrintScreen));
thread.SetApartmentState(ApartmentState.STA);
thread.Start(requestParam);
if (requestParam.Wait)
{
thread.Join();
FileInfo result=new FileInfo(requestParam.SavePath);
long minSize=1 * 1024;// 太小可能是空白圖,重抓
int maxRepeat=2;
while ((!result.Exists || result.Length <=minSize) && maxRepeat > 0)
{
thread=new Thread(new ParameterizedThreadStart(do_PrintScreen));
thread.SetApartmentState(ApartmentState.STA);
thread.Start(requestParam);
thread.Join();
maxRepeat--;
}
}
}
2、模擬瀏覽器WebBrowser
void do_PrintScreen(object param)
{
try
{
ScreenShotParam screenShotParam=(ScreenShotParam)param;
string requestUrl=screenShotParam.Url;
string savePath=screenShotParam.SavePath;
WebBrowser wb=new WebBrowser();
wb.ScrollBarsEnabled=false;
wb.ScriptErrorsSuppressed=true;
wb.Navigate(requestUrl);
logger.Debug("wb.Navigate");
DateTime startTime=DateTime.Now;
TimeSpan waitTime=new TimeSpan(0, 0, 0, 10, 0);// 10 second
while (wb.ReadyState !=WebBrowserReadyState.Complete)
{
Application.DoEvents();
if (DateTime.Now - startTime > waitTime)
{
wb.Dispose();
logger.Debug("wb.Dispose() timeout");
return;
}
}
wb.Width=screenShotParam.Left + screenShotParam.Width + screenShotParam.Left; // wb.Document.Body.ScrollRectangle.Width (避掉左右側(cè)的邊線);
wb.Height=screenShotParam.Top + screenShotParam.Height; // wb.Document.Body.ScrollRectangle.Height;
wb.ScrollBarsEnabled=false;
wb.Document.Body.Style="overflow:hidden";//hide scroll bar
var doc=(wb.Document.DomDocument) as mshtml.IHTMLDocument2;
var style=doc.createStyleSheet("", 0);
style.cssText=@"img { border-style: none; }";
Bitmap bitmap=new Bitmap(wb.Width, wb.Height);
wb.DrawToBitmap(bitmap, new Rectangle(0, 0, wb.Width, wb.Height));
wb.Dispose();
logger.Debug("wb.Dispose()");
bitmap=CutImage(bitmap, new Rectangle(screenShotParam.Left, screenShotParam.Top, screenShotParam.Width, screenShotParam.Height));
bool needResize=screenShotParam.Width > screenShotParam.ResizeMaxWidth || screenShotParam.Height > screenShotParam.ResizeMaxWidth;
if (needResize)
{
double greaterLength=bitmap.Width > bitmap.Height ? bitmap.Width : bitmap.Height;
double ratio=screenShotParam.ResizeMaxWidth / greaterLength;
bitmap=Resize(bitmap, ratio);
}
bitmap.Save(savePath, System.Drawing.Imaging.ImageFormat.Gif);
bitmap.Dispose();
logger.Debug("bitmap.Dispose();");
logger.Debug("finish");
}
catch (Exception ex)
{
logger.Info($"exception: {ex.Message}");
}
}
3、截圖操作
private static Bitmap CutImage(Bitmap source, Rectangle section)
{
// An empty bitmap which will hold the cropped image
Bitmap bmp=new Bitmap(section.Width, section.Height);
//using (Bitmap bmp=new Bitmap(section.Width, section.Height))
{
Graphics g=Graphics.FromImage(bmp);
// Draw the given area (section) of the source image
// at location 0,0 on the empty bitmap (bmp)
g.DrawImage(source, 0, 0, section, GraphicsUnit.Pixel);
return bmp;
}
}
private static Bitmap Resize(Bitmap originImage, Double times)
{
int width=Convert.ToInt32(originImage.Width * times);
int height=Convert.ToInt32(originImage.Height * times);
return ResizeProcess(originImage, originImage.Width, originImage.Height, width, height);
}
public static string ScreenShotAndSaveAmazonS3(string account, string locale, Guid rule_ID, Guid template_ID)
{
//新的Template
var url=string.Format("https://xxxx/public/previewtemplate?showTemplateName=0&locale={0}&inputTemplateId={1}&inputThemeId=&Account={2}",
locale,
template_ID,
account
);
var tempPath=Tools.GetAppSetting("TempPath");
//路徑準(zhǔn)備
var userPath=AmazonS3.GetS3UploadDirectory(account, locale, AmazonS3.S3SubFolder.Template);
var fileName=string.Format("{0}.gif", template_ID);
var fullFilePath=Path.Combine(userPath.LocalDirectoryPath, fileName);
logger.Debug("userPath: {0}, fileName: {1}, fullFilePath: {2}, url:{3}", userPath, fileName, fullFilePath, url);
//開始截圖,並暫存在本機(jī)
var screen=new Screen();
screen.ScreenShot(url, fullFilePath);
//將截圖,儲(chǔ)存到 Amazon S3
//var previewImageUrl=AmazonS3.UploadFile(fullFilePath, userPath.RemotePath + fileName);
return string.Empty;
}
using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace PrintScreen.Common
{
public class Screen
{
protected static NLog.Logger logger=NLog.LogManager.GetCurrentClassLogger();
public void ScreenShot(string url, string path
, int width=400, int height=300
, int left=50, int top=50
, int resizeMaxWidth=200, int wait=1)
{
if (!string.IsOrEmpty(url) && !string.IsOrEmpty(path))
{
ScreenShotParam requestParam=new ScreenShotParam
{
Url=url,
SavePath=path,
Width=width,
Height=height,
Left=left,
Top=top,
ResizeMaxWidth=resizeMaxWidth,
Wait=wait !=0
};
startPrintScreen(requestParam);
}
}
void startPrintScreen(ScreenShotParam requestParam)
{
Thread thread=new Thread(new ParameterizedThreadStart(do_PrintScreen));
thread.SetApartmentState(ApartmentState.STA);
thread.Start(requestParam);
if (requestParam.Wait)
{
thread.Join();
FileInfo result=new FileInfo(requestParam.SavePath);
long minSize=1 * 1024;// 太小可能是空白圖,重抓
int maxRepeat=2;
while ((!result.Exists || result.Length <=minSize) && maxRepeat > 0)
{
thread=new Thread(new ParameterizedThreadStart(do_PrintScreen));
thread.SetApartmentState(ApartmentState.STA);
thread.Start(requestParam);
thread.Join();
maxRepeat--;
}
}
}
void do_PrintScreen(object param)
{
try
{
ScreenShotParam screenShotParam=(ScreenShotParam)param;
string requestUrl=screenShotParam.Url;
string savePath=screenShotParam.SavePath;
WebBrowser wb=new WebBrowser();
wb.ScrollBarsEnabled=false;
wb.ScriptErrorsSuppressed=true;
wb.Navigate(requestUrl);
logger.Debug("wb.Navigate");
DateTime startTime=DateTime.Now;
TimeSpan waitTime=new TimeSpan(0, 0, 0, 10, 0);// 10 second
while (wb.ReadyState !=WebBrowserReadyState.Complete)
{
Application.DoEvents();
if (DateTime.Now - startTime > waitTime)
{
wb.Dispose();
logger.Debug("wb.Dispose() timeout");
return;
}
}
wb.Width=screenShotParam.Left + screenShotParam.Width + screenShotParam.Left; // wb.Document.Body.ScrollRectangle.Width (避掉左右側(cè)的邊線);
wb.Height=screenShotParam.Top + screenShotParam.Height; // wb.Document.Body.ScrollRectangle.Height;
wb.ScrollBarsEnabled=false;
wb.Document.Body.Style="overflow:hidden";//hide scroll bar
var doc=(wb.Document.DomDocument) as mshtml.IHTMLDocument2;
var style=doc.createStyleSheet("", 0);
style.cssText=@"img { border-style: none; }";
Bitmap bitmap=new Bitmap(wb.Width, wb.Height);
wb.DrawToBitmap(bitmap, new Rectangle(0, 0, wb.Width, wb.Height));
wb.Dispose();
logger.Debug("wb.Dispose()");
bitmap=CutImage(bitmap, new Rectangle(screenShotParam.Left, screenShotParam.Top, screenShotParam.Width, screenShotParam.Height));
bool needResize=screenShotParam.Width > screenShotParam.ResizeMaxWidth || screenShotParam.Height > screenShotParam.ResizeMaxWidth;
if (needResize)
{
double greaterLength=bitmap.Width > bitmap.Height ? bitmap.Width : bitmap.Height;
double ratio=screenShotParam.ResizeMaxWidth / greaterLength;
bitmap=Resize(bitmap, ratio);
}
bitmap.Save(savePath, System.Drawing.Imaging.ImageFormat.Gif);
bitmap.Dispose();
logger.Debug("bitmap.Dispose();");
logger.Debug("finish");
}
catch (Exception ex)
{
logger.Info($"exception: {ex.Message}");
}
}
private static Bitmap CutImage(Bitmap source, Rectangle section)
{
// An empty bitmap which will hold the cropped image
Bitmap bmp=new Bitmap(section.Width, section.Height);
//using (Bitmap bmp=new Bitmap(section.Width, section.Height))
{
Graphics g=Graphics.FromImage(bmp);
// Draw the given area (section) of the source image
// at location 0,0 on the empty bitmap (bmp)
g.DrawImage(source, 0, 0, section, GraphicsUnit.Pixel);
return bmp;
}
}
private static Bitmap Resize(Bitmap originImage, Double times)
{
int width=Convert.ToInt32(originImage.Width * times);
int height=Convert.ToInt32(originImage.Height * times);
return ResizeProcess(originImage, originImage.Width, originImage.Height, width, height);
}
private static Bitmap ResizeProcess(Bitmap originImage, int oriwidth, int oriheight, int width, int height)
{
Bitmap resizedbitmap=new Bitmap(width, height);
//using (Bitmap resizedbitmap=new Bitmap(width, height))
{
Graphics g=Graphics.FromImage(resizedbitmap);
g.InterpolationMode=System.Drawing.Drawing2D.InterpolationMode.High;
g.SmoothingMode=System.Drawing.Drawing2D.SmoothingMode.HighQuality;
g.Clear(Color.Transparent);
g.DrawImage(originImage, new Rectangle(0, 0, width, height), new Rectangle(0, 0, oriwidth, oriheight), GraphicsUnit.Pixel);
return resizedbitmap;
}
}
}
class ScreenShotParam
{
public string Url { get; set; }
public string SavePath { get; set; }
public int Width { get; set; }
public int Height { get; set; }
public int Left { get; set; }
public int Top { get; set; }
/// <summary>
/// 長(zhǎng)邊縮到指定長(zhǎng)度
/// </summary>
public int ResizeMaxWidth { get; set; }
public bool Wait { get; set; }
}
}
完成,達(dá)到預(yù)期的效果。
*請(qǐng)認(rèn)真填寫需求信息,我們會(huì)在24小時(shí)內(nèi)與您取得聯(lián)系。