(I'm testing with Protractor and Jasmine, and I've also included image-diff and node-canvas in my project.)
I need to compare two images and make sure they are the same. One is saved in my file structure and the other is created from canvas. I am able to convert the canvas to image and also load the image from the file. Here's what I have:
var imagediff = require('../node_modules/js-imagediff/js/imagediff.js');
var Canvas = require('canvas');
var fs = require('fs');
var path = require('path');
beforeEach(function () {
jasmine.addMatchers(imagediff.jasmine);
});
function loadImage (url, callback) {
var image;
fs.readFile(url, function (error, data) {
if (error) throw error;
image = new Canvas.Image();
image.onload = function () {
callback(image);
};
image.src = data;
});
return image;
}
it('should work', function () {
//executeScript is needed to get the canvas element and convert it
browser.driver.executeScript(function() {
var can = document.querySelector('#workspace-canvas');
var ctx = can.getContext("2d");
var data = can.toDataURL("image/png");
var img = new Image();
img.src = data;
//this code below shows that the image was converted properly
// var link = document.createElement('a');
// link.href = img.src;
// link.download = 'image1.png';
// link.click();
return data;
}).then(function(result) {
newData = result;
var imgPath = path.join(__dirname, './images/image1.png');
loadImage(imgPath, function(image) {
console.log('loadImage');
var canvas = new Canvas();
canvas.width = image.width;
canvas.height = image.height;
var ctx = canvas.getContext("2d");
ctx.drawImage(image, 0, 0);
var data = canvas.toDataURL("image/png");
oldData = data;
//TODO: do a comparison here!
done();
});
});
My question is how do I compare the two images and make sure they are the same? I thought comparing the data URI would work but it doesn't. I'd really like to use image-diff but I'm not sure how to do that. Please help me!
The API of imagediff, has the imagediff.equal(a,b)
function, that gets 2 Image
objects, which should help you in this case.
If this won't help you, you could always md5 hash both of them and make sure the checksums are equal, more info on this md5, checksum.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With