Implement a pixel comparison service based on casperjs and resemble.js
This article mainly introduces you to the relevant information about implementing a pixel comparison service based on casperjs and resemble.js. The article introduces it in detail through the example code. It has certain reference learning value for everyone's study or work. It needs Friends, come and study together.
Preface
This time I share a node service that provides pixel comparison between the design draft and the front-end page, aiming to provide testing or The front-end personnel complete an auxiliary test themselves. Believe me, under the comparison at the pixel level, the degree of restoration of the design draft on the web page will immediately become apparent. Not much to say below, let’s take a look at the detailed introduction.
Effect preview
## Pre-knowledge
- casperjs: written based on PhantomJS. It provides an interfaceless browser internally. Simply put, you can use it to complete the operation of simulating a human to operate the browser in the form of code, which involves various mouse events and many other functions. This time it is mainly used. It comes with a screenshot function.
- resemble.js: Image pixel comparison tool. The simple understanding of the calling method is that two images are passed in and a composite image is returned with comparison parameters such as difference and so on. The basic implementation idea can be understood as converting the image to canvas, obtaining its image pixels, and then comparing each pixel.
the whole idea
From the picture above, we should be able to sort out a rough process:
- Receive the design draft image and the website address and node information that need to be intercepted from the front-end page
- Save the design draft to the images folder
- Open the sub-process, start casperjs, and complete the interception of the target website
- After intercepting, request form.html to fill in the image address information and re-transmit it back to the server
- The server obtains the image information and compares the intercepted image with the design draft through resemblejs
- The results are returned to the front-end page
Implementation details
const MIME_TYPE = { "css": "text/css", "gif": "image/gif", "html": "text/html", "ico": "image/x-icon", "jpeg": "image/jpeg", "jpg": "image/jpg", "js": "text/javascript", "json": "application/json", "pdf": "application/pdf", "png": "image/png", "svg": "image/svg+xml", "swf": "application/x-shockwave-flash", "tiff": "image/tiff", "txt": "text/plain", "wav": "audio/x-wav", "wma": "audio/x-ms-wma", "wmv": "video/x-ms-wmv", "xml": "text/xml" } function sendFile(filePath, res) { fs.open(filePath, 'r+', function(err){ //根据路径打开文件 if(err){ send404(res) }else{ let ext = path.extname(filePath) ext = ext ? ext.slice(1) : 'unknown' let contentType = MIME_TYPE[ext] || "text/plain" //匹配文件类型 fs.readFile(filePath,function(err,data){ if(err){ send500(res) }else{ res.writeHead(200,{'content-type':contentType}) res.end(data) } }) } }) }Parse the form and store the pictures into the images folder
const multiparty = require('multiparty') //解析表单 let form = new multiparty.Form() form.parse(req, function (err, fields, files) { let filename = files['file'][0].originalFilename, targetPath = __dirname + '/images/' + filename, if(filename){ fs.createReadStream(files['file'][0].path).pipe(fs.createWriteStream(targetPath)) ... } })The uploaded image can be saved by creating a readable stream to read the file content, and then writing it to the specified path through pipe.
Run casperjs
const { spawn } = require('child_process') spawn('casperjs', ['casper.js', filename, captureUrl, selector, id]) casperjs.stdout.on('data', (data) => { ... })You can create a child process through spawn to start casperjs, you can also use exec etc.
Take a screenshot and submit the data to form.html
const system = require('system') const host = 'http://10.2.45.110:3033' const casper = require('casper').create({ // 浏览器窗口大小 viewportSize: { width: 1920, height: 4080 } }) const fileName = decodeURIComponent(system.args[4]) const url = decodeURIComponent(system.args[5]) const selector = decodeURIComponent(system.args[6]) const id = decodeURIComponent(system.args[7]) const time = new Date().getTime() casper.start(url) casper.then(function() { console.log('正在截图请稍后') this.captureSelector('./images/casper'+ id + time +'.png', selector) }) casper.then(function() { casper.start(host + '/form.html', function() { this.fill('form#contact-form', { 'diff': './images/casper'+ id + time +'.png', 'point': './images/' + fileName, 'id': id }, true) }) }) casper.run()The code is relatively simple, the main process Just open a page, then pass your operation in then, and finally execute run. During this process, I didn't quite know how to communicate with the node service, so I chose to open another page. . If you want to study in depth, you can check out the official website of casperjs which is very detailed!
Perform pixel comparison and return data through resemble.js
function complete(data) { let imgName = 'diff'+ new Date().getTime() +'.png', imgUrl, analysisTime = data.analysisTime, misMatchPercentage = data.misMatchPercentage, resultUrl = './images/' + imgName fs.writeFileSync(resultUrl, data.getBuffer()) imgObj = { ... } let resEnd = resObj[id] // 找回最开始的res返回给页面数据 resEnd.writeHead(200, {'Content-type':'application/json'}) resEnd.end(JSON.stringify(imgObj)) } let result = resemble(diff).compareTo(point).ignoreColors().onComplete(complete)
这其中涉及到了一个点,即我现在所得到的结果要返回给最初的请求里,而从一开始的请求到现在我已经中转了多次,导致我现在找不到我最初的返回体res了。想了很久只能暂时采用了设定全局对象,在接收最初的请求后将请求者的ip和时间戳设定为唯一id存为该对象的key,value为当前的res。同时整个中转流程中时刻传递id,最后通过调用resObj[id]来得到一开始的返回体,返回数据。这个方法我不认为是最优解,但是鉴于我现在想不出来好方法为了跑通整个服务不得已。。如果有新的思路请务必告知!!
部署
安装PhantomJS(osx)
官网下载: phantomjs-2.1.1-macosx.zip
解压路径:/User/xxx/phantomjs-2.1.1-macosx
添加环境变量:~/.bash_profile 文件中添加
export PATH="$PATH:/Users/xxx/phantomjs-2.1.1-macosx/bin"
terminal输入:phantomjs --version
能看到版本号即安装成功
安装casperjs
brew update && brew install casperjs
安装resemble.js
cnpm i resemblejs //已写进packjson可不用安装 brew install pkg-config cairo libpng jpeg giflib cnpm i canvas //node内运行canvas
node服务
git clone https://github.com/Aaaaaaaty/gui-auto-test.git cd gui-auto-test cnpm i cd pxdiff nodemon server.js
打开http://localhost:3033/index.html
以上就是本文的全部内容,希望对大家的学习有所帮助,更多相关内容请关注PHP中文网!
相关推荐:
The above is the detailed content of Implement a pixel comparison service based on casperjs and resemble.js. For more information, please follow other related articles on the PHP Chinese website!

JavaScript core data types are consistent in browsers and Node.js, but are handled differently from the extra types. 1) The global object is window in the browser and global in Node.js. 2) Node.js' unique Buffer object, used to process binary data. 3) There are also differences in performance and time processing, and the code needs to be adjusted according to the environment.

JavaScriptusestwotypesofcomments:single-line(//)andmulti-line(//).1)Use//forquicknotesorsingle-lineexplanations.2)Use//forlongerexplanationsorcommentingoutblocksofcode.Commentsshouldexplainthe'why',notthe'what',andbeplacedabovetherelevantcodeforclari

The main difference between Python and JavaScript is the type system and application scenarios. 1. Python uses dynamic types, suitable for scientific computing and data analysis. 2. JavaScript adopts weak types and is widely used in front-end and full-stack development. The two have their own advantages in asynchronous programming and performance optimization, and should be decided according to project requirements when choosing.

Whether to choose Python or JavaScript depends on the project type: 1) Choose Python for data science and automation tasks; 2) Choose JavaScript for front-end and full-stack development. Python is favored for its powerful library in data processing and automation, while JavaScript is indispensable for its advantages in web interaction and full-stack development.

Python and JavaScript each have their own advantages, and the choice depends on project needs and personal preferences. 1. Python is easy to learn, with concise syntax, suitable for data science and back-end development, but has a slow execution speed. 2. JavaScript is everywhere in front-end development and has strong asynchronous programming capabilities. Node.js makes it suitable for full-stack development, but the syntax may be complex and error-prone.

JavaScriptisnotbuiltonCorC ;it'saninterpretedlanguagethatrunsonenginesoftenwritteninC .1)JavaScriptwasdesignedasalightweight,interpretedlanguageforwebbrowsers.2)EnginesevolvedfromsimpleinterpreterstoJITcompilers,typicallyinC ,improvingperformance.

JavaScript can be used for front-end and back-end development. The front-end enhances the user experience through DOM operations, and the back-end handles server tasks through Node.js. 1. Front-end example: Change the content of the web page text. 2. Backend example: Create a Node.js server.

Choosing Python or JavaScript should be based on career development, learning curve and ecosystem: 1) Career development: Python is suitable for data science and back-end development, while JavaScript is suitable for front-end and full-stack development. 2) Learning curve: Python syntax is concise and suitable for beginners; JavaScript syntax is flexible. 3) Ecosystem: Python has rich scientific computing libraries, and JavaScript has a powerful front-end framework.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

SublimeText3 Chinese version
Chinese version, very easy to use

VSCode Windows 64-bit Download
A free and powerful IDE editor launched by Microsoft

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

Notepad++7.3.1
Easy-to-use and free code editor

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.
