Best JavaScript code snippet using differencify
barriers.js
Source:barriers.js
...65 y: this.y + this.image_size66 };67 push();68 imageMode(CENTER);69 image(this.left_image_1, barrier_left_1.x, barrier_left_1.y, this.image_size, this.image_size);70 image(this.left_image_2, barrier_left_2.x, barrier_left_2.y, this.image_size, this.image_size);71 image(this.left_image_3, barrier_left_3.x, barrier_left_3.y, this.image_size, this.image_size);72 image(this.right_image_1, barrier_right_1.x, barrier_right_1.y, this.image_size, this.image_size);73 image(this.right_image_2, barrier_right_2.x, barrier_right_2.y, this.image_size, this.image_size);74 image(this.right_image_3, barrier_right_3.x, barrier_right_3.y, this.image_size, this.image_size);75 image(this.middle_image_1, barrier_midle_1.x, barrier_midle_1.y, this.image_size, this.image_size);76 image(this.middle_image_2, barrier_midle_2.x, barrier_midle_2.y, this.image_size, this.image_size);77 if (this.down_damaged == 0 && this.up_damaged != this.middle_damage_max) {78 image(image_barrier_bottom_edge, barrier_midle_3.x, barrier_midle_3.y, this.image_size, this.image_size);79 }80 pop();81 }82 update() {83 if(this.left_up_damaged + this.left_down_damaged >= this.left_damage_max){//Prevent damage beyond the limit.84 this.left_up_damaged = this.left_damage_max;85 this.left_down_damaged = 0;86 }87 if(this.right_up_damaged + this.right_down_damaged >= this.right_damage_max){88 this.right_up_damaged = this.right_damage_max;89 this.right_down_damaged = 0;90 }91 if(this.up_damaged + this.down_damaged >= this.middle_damage_max){92 this.up_damaged = this.middle_damage_max;...
api-native-image-spec.js
Source:api-native-image-spec.js
1'use strict'2/* eslint-disable no-unused-expressions */3const {expect} = require('chai')4const {nativeImage} = require('electron')5const path = require('path')6describe('nativeImage module', () => {7 const ImageFormat = {8 PNG: 'png',9 JPEG: 'jpeg'10 }11 const images = [12 {13 filename: 'logo.png',14 format: ImageFormat.PNG,15 hasAlphaChannel: true,16 hasDataUrl: false,17 width: 538,18 height: 19019 },20 {21 dataUrl: 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAAC0lEQVQYlWNgAAIAAAUAAdafFs0AAAAASUVORK5CYII=',22 filename: '1x1.png',23 format: ImageFormat.PNG,24 hasAlphaChannel: true,25 hasDataUrl: true,26 height: 1,27 width: 128 },29 {30 dataUrl: 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAIAAAACCAIAAAD91JpzAAAAFklEQVQYlWP8//8/AwMDEwMDAwMDAwAkBgMBBMzldwAAAABJRU5ErkJggg==',31 filename: '2x2.jpg',32 format: ImageFormat.JPEG,33 hasAlphaChannel: false,34 hasDataUrl: true,35 height: 2,36 width: 237 },38 {39 dataUrl: 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAMAAAADCAYAAABWKLW/AAAADElEQVQYlWNgIAoAAAAnAAGZWEMnAAAAAElFTkSuQmCC',40 filename: '3x3.png',41 format: ImageFormat.PNG,42 hasAlphaChannel: true,43 hasDataUrl: true,44 height: 3,45 width: 346 }47 ]48 /**49 * @param {?string} filename50 * @returns {?string} Full path.51 */52 const getImagePathFromFilename = (filename) => {53 return (filename === null) ? null54 : path.join(__dirname, 'fixtures', 'assets', filename)55 }56 /**57 * @param {!Object} image58 * @param {Object} filters59 * @returns {boolean}60 */61 const imageMatchesTheFilters = (image, filters = null) => {62 if (filters === null) {63 return true64 }65 return Object.entries(filters)66 .every(([key, value]) => image[key] === value)67 }68 /**69 * @param {!Object} filters70 * @returns {!Array} A matching images list.71 */72 const getImages = (filters) => {73 const matchingImages = images74 .filter(i => imageMatchesTheFilters(i, filters))75 // Add `.path` property to every image.76 matchingImages77 .forEach(i => { i.path = getImagePathFromFilename(i.filename) })78 return matchingImages79 }80 /**81 * @param {!Object} filters82 * @returns {Object} A matching image if any.83 */84 const getImage = (filters) => {85 const matchingImages = getImages(filters)86 let matchingImage = null87 if (matchingImages.length > 0) {88 matchingImage = matchingImages[0]89 }90 return matchingImage91 }92 describe('createEmpty()', () => {93 it('returns an empty image', () => {94 const empty = nativeImage.createEmpty()95 expect(empty.isEmpty())96 expect(empty.getAspectRatio()).to.equal(1)97 expect(empty.toDataURL()).to.equal('data:image/png;base64,')98 expect(empty.toDataURL({scaleFactor: 2.0})).to.equal('data:image/png;base64,')99 expect(empty.getSize()).to.deep.equal({width: 0, height: 0})100 expect(empty.getBitmap()).to.be.empty101 expect(empty.getBitmap({scaleFactor: 2.0})).to.be.empty102 expect(empty.toBitmap()).to.be.empty103 expect(empty.toBitmap({scaleFactor: 2.0})).to.be.empty104 expect(empty.toJPEG(100)).to.be.empty105 expect(empty.toPNG()).to.be.empty106 expect(empty.toPNG({scaleFactor: 2.0})).to.be.empty107 if (process.platform === 'darwin') {108 expect(empty.getNativeHandle()).to.be.empty109 }110 })111 })112 describe('createFromBuffer(buffer, scaleFactor)', () => {113 it('returns an empty image when the buffer is empty', () => {114 expect(nativeImage.createFromBuffer(Buffer.from([])).isEmpty())115 })116 it('returns an image created from the given buffer', () => {117 const imageA = nativeImage.createFromPath(path.join(__dirname, 'fixtures', 'assets', 'logo.png'))118 const imageB = nativeImage.createFromBuffer(imageA.toPNG())119 expect(imageB.getSize()).to.deep.equal({width: 538, height: 190})120 expect(imageA.toBitmap().equals(imageB.toBitmap())).to.be.true121 const imageC = nativeImage.createFromBuffer(imageA.toJPEG(100))122 expect(imageC.getSize()).to.deep.equal({width: 538, height: 190})123 const imageD = nativeImage.createFromBuffer(imageA.toBitmap(),124 {width: 538, height: 190})125 expect(imageD.getSize()).to.deep.equal({width: 538, height: 190})126 const imageE = nativeImage.createFromBuffer(imageA.toBitmap(),127 {width: 100, height: 200})128 expect(imageE.getSize()).to.deep.equal({width: 100, height: 200})129 const imageF = nativeImage.createFromBuffer(imageA.toBitmap())130 expect(imageF.isEmpty())131 const imageG = nativeImage.createFromBuffer(imageA.toPNG(),132 {width: 100, height: 200})133 expect(imageG.getSize()).to.deep.equal({width: 538, height: 190})134 const imageH = nativeImage.createFromBuffer(imageA.toJPEG(100),135 {width: 100, height: 200})136 expect(imageH.getSize()).to.deep.equal({width: 538, height: 190})137 const imageI = nativeImage.createFromBuffer(imageA.toBitmap(),138 {width: 538, height: 190, scaleFactor: 2.0})139 expect(imageI.getSize()).to.deep.equal({width: 269, height: 95})140 })141 })142 describe('createFromDataURL(dataURL)', () => {143 it('returns an empty image from the empty string', () => {144 expect(nativeImage.createFromDataURL('').isEmpty())145 })146 it('returns an image created from the given string', () => {147 const imagesData = getImages({hasDataUrl: true})148 for (const imageData of imagesData) {149 const imageFromPath = nativeImage.createFromPath(imageData.path)150 const imageFromDataUrl = nativeImage.createFromDataURL(imageData.dataUrl)151 expect(imageFromDataUrl.isEmpty())152 expect(imageFromDataUrl.getSize()).to.deep.equal(imageFromPath.getSize())153 expect(imageFromDataUrl.toBitmap()).to.satisfy(154 bitmap => imageFromPath.toBitmap().equals(bitmap))155 expect(imageFromDataUrl.toDataURL()).to.equal(imageFromPath.toDataURL())156 }157 })158 })159 describe('toDataURL()', () => {160 it('returns a PNG data URL', () => {161 const imagesData = getImages({hasDataUrl: true})162 for (const imageData of imagesData) {163 const imageFromPath = nativeImage.createFromPath(imageData.path)164 const scaleFactors = [1.0, 2.0]165 for (const scaleFactor of scaleFactors) {166 expect(imageFromPath.toDataURL({scaleFactor})).to.equal(imageData.dataUrl)167 }168 }169 })170 it('returns a data URL at 1x scale factor by default', () => {171 const imageData = getImage({filename: 'logo.png'})172 const image = nativeImage.createFromPath(imageData.path)173 const imageOne = nativeImage.createFromBuffer(image.toPNG(), {174 width: image.getSize().width,175 height: image.getSize().height,176 scaleFactor: 2.0177 })178 expect(imageOne.getSize()).to.deep.equal(179 {width: imageData.width / 2, height: imageData.height / 2})180 const imageTwo = nativeImage.createFromDataURL(imageOne.toDataURL())181 expect(imageTwo.getSize()).to.deep.equal(182 {width: imageData.width, height: imageData.height})183 expect(imageOne.toBitmap().equals(imageTwo.toBitmap())).to.be.true184 })185 it('supports a scale factor', () => {186 const imageData = getImage({filename: 'logo.png'})187 const image = nativeImage.createFromPath(imageData.path)188 const expectedSize = {width: imageData.width, height: imageData.height}189 const imageFromDataUrlOne = nativeImage.createFromDataURL(190 image.toDataURL({scaleFactor: 1.0}))191 expect(imageFromDataUrlOne.getSize()).to.deep.equal(expectedSize)192 const imageFromDataUrlTwo = nativeImage.createFromDataURL(193 image.toDataURL({scaleFactor: 2.0}))194 expect(imageFromDataUrlTwo.getSize()).to.deep.equal(expectedSize)195 })196 })197 describe('toPNG()', () => {198 it('returns a buffer at 1x scale factor by default', () => {199 const imageData = getImage({filename: 'logo.png'})200 const imageA = nativeImage.createFromPath(imageData.path)201 const imageB = nativeImage.createFromBuffer(imageA.toPNG(), {202 width: imageA.getSize().width,203 height: imageA.getSize().height,204 scaleFactor: 2.0205 })206 expect(imageB.getSize()).to.deep.equal(207 {width: imageData.width / 2, height: imageData.height / 2})208 const imageC = nativeImage.createFromBuffer(imageB.toPNG())209 expect(imageC.getSize()).to.deep.equal(210 {width: imageData.width, height: imageData.height})211 expect(imageB.toBitmap().equals(imageC.toBitmap())).to.be.true212 })213 it('supports a scale factor', () => {214 const imageData = getImage({filename: 'logo.png'})215 const image = nativeImage.createFromPath(imageData.path)216 const imageFromBufferOne = nativeImage.createFromBuffer(217 image.toPNG({scaleFactor: 1.0}))218 expect(imageFromBufferOne.getSize()).to.deep.equal(219 {width: imageData.width, height: imageData.height})220 const imageFromBufferTwo = nativeImage.createFromBuffer(221 image.toPNG({scaleFactor: 2.0}), {scaleFactor: 2.0})222 expect(imageFromBufferTwo.getSize()).to.deep.equal(223 {width: imageData.width / 2, height: imageData.height / 2})224 })225 })226 describe('createFromPath(path)', () => {227 it('returns an empty image for invalid paths', () => {228 expect(nativeImage.createFromPath('').isEmpty())229 expect(nativeImage.createFromPath('does-not-exist.png').isEmpty())230 expect(nativeImage.createFromPath('does-not-exist.ico').isEmpty())231 expect(nativeImage.createFromPath(__dirname).isEmpty())232 expect(nativeImage.createFromPath(__filename).isEmpty())233 })234 it('loads images from paths relative to the current working directory', () => {235 const imagePath = `.${path.sep}${path.join('spec', 'fixtures', 'assets', 'logo.png')}`236 const image = nativeImage.createFromPath(imagePath)237 expect(image.isEmpty()).to.be.false238 expect(image.getSize()).to.deep.equal({width: 538, height: 190})239 })240 it('loads images from paths with `.` segments', () => {241 const imagePath = `${path.join(__dirname, 'fixtures')}${path.sep}.${path.sep}${path.join('assets', 'logo.png')}`242 const image = nativeImage.createFromPath(imagePath)243 expect(image.isEmpty()).to.be.false244 expect(image.getSize()).to.deep.equal({width: 538, height: 190})245 })246 it('loads images from paths with `..` segments', () => {247 const imagePath = `${path.join(__dirname, 'fixtures', 'api')}${path.sep}..${path.sep}${path.join('assets', 'logo.png')}`248 const image = nativeImage.createFromPath(imagePath)249 expect(image.isEmpty()).to.be.false250 expect(image.getSize()).to.deep.equal({width: 538, height: 190})251 })252 it('Gets an NSImage pointer on macOS', function () {253 if (process.platform !== 'darwin') {254 // FIXME(alexeykuzmin): Skip the test.255 // this.skip()256 return257 }258 const imagePath = `${path.join(__dirname, 'fixtures', 'api')}${path.sep}..${path.sep}${path.join('assets', 'logo.png')}`259 const image = nativeImage.createFromPath(imagePath)260 const nsimage = image.getNativeHandle()261 expect(nsimage).to.have.lengthOf(8)262 // If all bytes are null, that's Bad263 const allBytesAreNotNull = nsimage.reduce((acc, x) => acc || (x !== 0), false)264 expect(allBytesAreNotNull)265 })266 it('loads images from .ico files on Windows', function () {267 if (process.platform !== 'win32') {268 // FIXME(alexeykuzmin): Skip the test.269 // this.skip()270 return271 }272 const imagePath = path.join(__dirname, 'fixtures', 'assets', 'icon.ico')273 const image = nativeImage.createFromPath(imagePath)274 expect(image.isEmpty()).to.be.false275 expect(image.getSize()).to.deep.equal({width: 256, height: 256})276 })277 })278 describe('createFromNamedImage(name)', () => {279 it('returns empty for invalid options', () => {280 const image = nativeImage.createFromNamedImage('totally_not_real')281 expect(image.isEmpty())282 })283 it('returns empty on non-darwin platforms', function () {284 if (process.platform === 'darwin') {285 // FIXME(alexeykuzmin): Skip the test.286 // this.skip()287 return288 }289 const image = nativeImage.createFromNamedImage('NSActionTemplate')290 expect(image.isEmpty())291 })292 it('returns a valid image on darwin', function () {293 if (process.platform !== 'darwin') {294 // FIXME(alexeykuzmin): Skip the test.295 // this.skip()296 return297 }298 const image = nativeImage.createFromNamedImage('NSActionTemplate')299 expect(image.isEmpty()).to.be.false300 })301 it('returns allows an HSL shift for a valid image on darwin', function () {302 if (process.platform !== 'darwin') {303 // FIXME(alexeykuzmin): Skip the test.304 // this.skip()305 return306 }307 const image = nativeImage.createFromNamedImage('NSActionTemplate', [0.5, 0.2, 0.8])308 expect(image.isEmpty()).to.be.false309 })310 })311 describe('resize(options)', () => {312 it('returns a resized image', () => {313 const image = nativeImage.createFromPath(path.join(__dirname, 'fixtures', 'assets', 'logo.png'))314 for (const [resizeTo, expectedSize] of new Map([315 [{}, {width: 538, height: 190}],316 [{width: 269}, {width: 269, height: 95}],317 [{width: 600}, {width: 600, height: 212}],318 [{height: 95}, {width: 269, height: 95}],319 [{height: 200}, {width: 566, height: 200}],320 [{width: 80, height: 65}, {width: 80, height: 65}],321 [{width: 600, height: 200}, {width: 600, height: 200}],322 [{width: 0, height: 0}, {width: 0, height: 0}],323 [{width: -1, height: -1}, {width: 0, height: 0}]324 ])) {325 const actualSize = image.resize(resizeTo).getSize()326 expect(actualSize).to.deep.equal(expectedSize)327 }328 })329 it('returns an empty image when called on an empty image', () => {330 expect(nativeImage.createEmpty().resize({width: 1, height: 1}).isEmpty())331 expect(nativeImage.createEmpty().resize({width: 0, height: 0}).isEmpty())332 })333 it('supports a quality option', () => {334 const image = nativeImage.createFromPath(path.join(__dirname, 'fixtures', 'assets', 'logo.png'))335 const good = image.resize({width: 100, height: 100, quality: 'good'})336 const better = image.resize({width: 100, height: 100, quality: 'better'})337 const best = image.resize({width: 100, height: 100, quality: 'best'})338 expect(good.toPNG()).to.have.lengthOf.at.most(better.toPNG().length)339 expect(better.toPNG()).to.have.lengthOf.below(best.toPNG().length)340 })341 })342 describe('crop(bounds)', () => {343 it('returns an empty image when called on an empty image', () => {344 expect(nativeImage.createEmpty().crop({width: 1, height: 2, x: 0, y: 0}).isEmpty())345 expect(nativeImage.createEmpty().crop({width: 0, height: 0, x: 0, y: 0}).isEmpty())346 })347 it('returns an empty image when the bounds are invalid', () => {348 const image = nativeImage.createFromPath(path.join(__dirname, 'fixtures', 'assets', 'logo.png'))349 expect(image.crop({width: 0, height: 0, x: 0, y: 0}).isEmpty())350 expect(image.crop({width: -1, height: 10, x: 0, y: 0}).isEmpty())351 expect(image.crop({width: 10, height: -35, x: 0, y: 0}).isEmpty())352 expect(image.crop({width: 100, height: 100, x: 1000, y: 1000}).isEmpty())353 })354 it('returns a cropped image', () => {355 const image = nativeImage.createFromPath(path.join(__dirname, 'fixtures', 'assets', 'logo.png'))356 const cropA = image.crop({width: 25, height: 64, x: 0, y: 0})357 const cropB = image.crop({width: 25, height: 64, x: 30, y: 40})358 expect(cropA.getSize()).to.deep.equal({width: 25, height: 64})359 expect(cropB.getSize()).to.deep.equal({width: 25, height: 64})360 expect(cropA.toPNG().equals(cropB.toPNG())).to.be.false361 })362 })363 describe('getAspectRatio()', () => {364 it('returns an aspect ratio of an empty image', () => {365 expect(nativeImage.createEmpty().getAspectRatio()).to.equal(1.0)366 })367 it('returns an aspect ratio of an image', () => {368 const imageData = getImage({filename: 'logo.png'})369 // imageData.width / imageData.height = 2.831578947368421370 const expectedAspectRatio = 2.8315789699554443371 const image = nativeImage.createFromPath(imageData.path)372 expect(image.getAspectRatio()).to.equal(expectedAspectRatio)373 })374 })375 describe('addRepresentation()', () => {376 it('supports adding a buffer representation for a scale factor', () => {377 const image = nativeImage.createEmpty()378 const imageDataOne = getImage({width: 1, height: 1})379 image.addRepresentation({380 scaleFactor: 1.0,381 buffer: nativeImage.createFromPath(imageDataOne.path).toPNG()382 })383 const imageDataTwo = getImage({width: 2, height: 2})384 image.addRepresentation({385 scaleFactor: 2.0,386 buffer: nativeImage.createFromPath(imageDataTwo.path).toPNG()387 })388 const imageDataThree = getImage({width: 3, height: 3})389 image.addRepresentation({390 scaleFactor: 3.0,391 buffer: nativeImage.createFromPath(imageDataThree.path).toPNG()392 })393 image.addRepresentation({394 scaleFactor: 4.0,395 buffer: 'invalid'396 })397 expect(image.isEmpty()).to.be.false398 expect(image.getSize()).to.deep.equal({width: 1, height: 1})399 expect(image.toDataURL({scaleFactor: 1.0})).to.equal(imageDataOne.dataUrl)400 expect(image.toDataURL({scaleFactor: 2.0})).to.equal(imageDataTwo.dataUrl)401 expect(image.toDataURL({scaleFactor: 3.0})).to.equal(imageDataThree.dataUrl)402 expect(image.toDataURL({scaleFactor: 4.0})).to.equal(imageDataThree.dataUrl)403 })404 it('supports adding a data URL representation for a scale factor', () => {405 const image = nativeImage.createEmpty()406 const imageDataOne = getImage({width: 1, height: 1})407 image.addRepresentation({408 scaleFactor: 1.0,409 dataURL: imageDataOne.dataUrl410 })411 const imageDataTwo = getImage({width: 2, height: 2})412 image.addRepresentation({413 scaleFactor: 2.0,414 dataURL: imageDataTwo.dataUrl415 })416 const imageDataThree = getImage({width: 3, height: 3})417 image.addRepresentation({418 scaleFactor: 3.0,419 dataURL: imageDataThree.dataUrl420 })421 image.addRepresentation({422 scaleFactor: 4.0,423 dataURL: 'invalid'424 })425 expect(image.isEmpty()).to.be.false426 expect(image.getSize()).to.deep.equal({width: 1, height: 1})427 expect(image.toDataURL({scaleFactor: 1.0})).to.equal(imageDataOne.dataUrl)428 expect(image.toDataURL({scaleFactor: 2.0})).to.equal(imageDataTwo.dataUrl)429 expect(image.toDataURL({scaleFactor: 3.0})).to.equal(imageDataThree.dataUrl)430 expect(image.toDataURL({scaleFactor: 4.0})).to.equal(imageDataThree.dataUrl)431 })432 it('supports adding a representation to an existing image', () => {433 const imageDataOne = getImage({width: 1, height: 1})434 const image = nativeImage.createFromPath(imageDataOne.path)435 const imageDataTwo = getImage({width: 2, height: 2})436 image.addRepresentation({437 scaleFactor: 2.0,438 dataURL: imageDataTwo.dataUrl439 })440 const imageDataThree = getImage({width: 3, height: 3})441 image.addRepresentation({442 scaleFactor: 2.0,443 dataURL: imageDataThree.dataUrl444 })445 expect(image.toDataURL({scaleFactor: 1.0})).to.equal(imageDataOne.dataUrl)446 expect(image.toDataURL({scaleFactor: 2.0})).to.equal(imageDataTwo.dataUrl)447 })448 })...
test_images.py
Source:test_images.py
1import unittest2import tkinter3from test import support4from tkinter.test.support import AbstractTkTest, AbstractDefaultRootTest, requires_tcl5support.requires('gui')6class MiscTest(AbstractTkTest, unittest.TestCase):7 def test_image_types(self):8 image_types = self.root.image_types()9 self.assertIsInstance(image_types, tuple)10 self.assertIn('photo', image_types)11 self.assertIn('bitmap', image_types)12 def test_image_names(self):13 image_names = self.root.image_names()14 self.assertIsInstance(image_names, tuple)15class DefaultRootTest(AbstractDefaultRootTest, unittest.TestCase):16 def test_image_types(self):17 self.assertRaises(RuntimeError, tkinter.image_types)18 root = tkinter.Tk()19 image_types = tkinter.image_types()20 self.assertIsInstance(image_types, tuple)21 self.assertIn('photo', image_types)22 self.assertIn('bitmap', image_types)23 root.destroy()24 tkinter.NoDefaultRoot()25 self.assertRaises(RuntimeError, tkinter.image_types)26 def test_image_names(self):27 self.assertRaises(RuntimeError, tkinter.image_names)28 root = tkinter.Tk()29 image_names = tkinter.image_names()30 self.assertIsInstance(image_names, tuple)31 root.destroy()32 tkinter.NoDefaultRoot()33 self.assertRaises(RuntimeError, tkinter.image_names)34 def test_image_create_bitmap(self):35 self.assertRaises(RuntimeError, tkinter.BitmapImage)36 root = tkinter.Tk()37 image = tkinter.BitmapImage()38 self.assertIn(image.name, tkinter.image_names())39 root.destroy()40 tkinter.NoDefaultRoot()41 self.assertRaises(RuntimeError, tkinter.BitmapImage)42 def test_image_create_photo(self):43 self.assertRaises(RuntimeError, tkinter.PhotoImage)44 root = tkinter.Tk()45 image = tkinter.PhotoImage()46 self.assertIn(image.name, tkinter.image_names())47 root.destroy()48 tkinter.NoDefaultRoot()49 self.assertRaises(RuntimeError, tkinter.PhotoImage)50class BitmapImageTest(AbstractTkTest, unittest.TestCase):51 @classmethod52 def setUpClass(cls):53 AbstractTkTest.setUpClass.__func__(cls)54 cls.testfile = support.findfile('python.xbm', subdir='imghdrdata')55 def test_create_from_file(self):56 image = tkinter.BitmapImage('::img::test', master=self.root,57 foreground='yellow', background='blue',58 file=self.testfile)59 self.assertEqual(str(image), '::img::test')60 self.assertEqual(image.type(), 'bitmap')61 self.assertEqual(image.width(), 16)62 self.assertEqual(image.height(), 16)63 self.assertIn('::img::test', self.root.image_names())64 del image65 self.assertNotIn('::img::test', self.root.image_names())66 def test_create_from_data(self):67 with open(self.testfile, 'rb') as f:68 data = f.read()69 image = tkinter.BitmapImage('::img::test', master=self.root,70 foreground='yellow', background='blue',71 data=data)72 self.assertEqual(str(image), '::img::test')73 self.assertEqual(image.type(), 'bitmap')74 self.assertEqual(image.width(), 16)75 self.assertEqual(image.height(), 16)76 self.assertIn('::img::test', self.root.image_names())77 del image78 self.assertNotIn('::img::test', self.root.image_names())79 def assertEqualStrList(self, actual, expected):80 self.assertIsInstance(actual, str)81 self.assertEqual(self.root.splitlist(actual), expected)82 def test_configure_data(self):83 image = tkinter.BitmapImage('::img::test', master=self.root)84 self.assertEqual(image['data'], '-data {} {} {} {}')85 with open(self.testfile, 'rb') as f:86 data = f.read()87 image.configure(data=data)88 self.assertEqualStrList(image['data'],89 ('-data', '', '', '', data.decode('ascii')))90 self.assertEqual(image.width(), 16)91 self.assertEqual(image.height(), 16)92 self.assertEqual(image['maskdata'], '-maskdata {} {} {} {}')93 image.configure(maskdata=data)94 self.assertEqualStrList(image['maskdata'],95 ('-maskdata', '', '', '', data.decode('ascii')))96 def test_configure_file(self):97 image = tkinter.BitmapImage('::img::test', master=self.root)98 self.assertEqual(image['file'], '-file {} {} {} {}')99 image.configure(file=self.testfile)100 self.assertEqualStrList(image['file'],101 ('-file', '', '', '',self.testfile))102 self.assertEqual(image.width(), 16)103 self.assertEqual(image.height(), 16)104 self.assertEqual(image['maskfile'], '-maskfile {} {} {} {}')105 image.configure(maskfile=self.testfile)106 self.assertEqualStrList(image['maskfile'],107 ('-maskfile', '', '', '', self.testfile))108 def test_configure_background(self):109 image = tkinter.BitmapImage('::img::test', master=self.root)110 self.assertEqual(image['background'], '-background {} {} {} {}')111 image.configure(background='blue')112 self.assertEqual(image['background'], '-background {} {} {} blue')113 def test_configure_foreground(self):114 image = tkinter.BitmapImage('::img::test', master=self.root)115 self.assertEqual(image['foreground'],116 '-foreground {} {} #000000 #000000')117 image.configure(foreground='yellow')118 self.assertEqual(image['foreground'],119 '-foreground {} {} #000000 yellow')120class PhotoImageTest(AbstractTkTest, unittest.TestCase):121 @classmethod122 def setUpClass(cls):123 AbstractTkTest.setUpClass.__func__(cls)124 cls.testfile = support.findfile('python.gif', subdir='imghdrdata')125 def create(self):126 return tkinter.PhotoImage('::img::test', master=self.root,127 file=self.testfile)128 def colorlist(self, *args):129 if tkinter.TkVersion >= 8.6 and self.wantobjects:130 return args131 else:132 return tkinter._join(args)133 def check_create_from_file(self, ext):134 testfile = support.findfile('python.' + ext, subdir='imghdrdata')135 image = tkinter.PhotoImage('::img::test', master=self.root,136 file=testfile)137 self.assertEqual(str(image), '::img::test')138 self.assertEqual(image.type(), 'photo')139 self.assertEqual(image.width(), 16)140 self.assertEqual(image.height(), 16)141 self.assertEqual(image['data'], '')142 self.assertEqual(image['file'], testfile)143 self.assertIn('::img::test', self.root.image_names())144 del image145 self.assertNotIn('::img::test', self.root.image_names())146 def check_create_from_data(self, ext):147 testfile = support.findfile('python.' + ext, subdir='imghdrdata')148 with open(testfile, 'rb') as f:149 data = f.read()150 image = tkinter.PhotoImage('::img::test', master=self.root,151 data=data)152 self.assertEqual(str(image), '::img::test')153 self.assertEqual(image.type(), 'photo')154 self.assertEqual(image.width(), 16)155 self.assertEqual(image.height(), 16)156 self.assertEqual(image['data'], data if self.wantobjects157 else data.decode('latin1'))158 self.assertEqual(image['file'], '')159 self.assertIn('::img::test', self.root.image_names())160 del image161 self.assertNotIn('::img::test', self.root.image_names())162 def test_create_from_ppm_file(self):163 self.check_create_from_file('ppm')164 def test_create_from_ppm_data(self):165 self.check_create_from_data('ppm')166 def test_create_from_pgm_file(self):167 self.check_create_from_file('pgm')168 def test_create_from_pgm_data(self):169 self.check_create_from_data('pgm')170 def test_create_from_gif_file(self):171 self.check_create_from_file('gif')172 def test_create_from_gif_data(self):173 self.check_create_from_data('gif')174 @requires_tcl(8, 6)175 def test_create_from_png_file(self):176 self.check_create_from_file('png')177 @requires_tcl(8, 6)178 def test_create_from_png_data(self):179 self.check_create_from_data('png')180 def test_configure_data(self):181 image = tkinter.PhotoImage('::img::test', master=self.root)182 self.assertEqual(image['data'], '')183 with open(self.testfile, 'rb') as f:184 data = f.read()185 image.configure(data=data)186 self.assertEqual(image['data'], data if self.wantobjects187 else data.decode('latin1'))188 self.assertEqual(image.width(), 16)189 self.assertEqual(image.height(), 16)190 def test_configure_format(self):191 image = tkinter.PhotoImage('::img::test', master=self.root)192 self.assertEqual(image['format'], '')193 image.configure(file=self.testfile, format='gif')194 self.assertEqual(image['format'], ('gif',) if self.wantobjects195 else 'gif')196 self.assertEqual(image.width(), 16)197 self.assertEqual(image.height(), 16)198 def test_configure_file(self):199 image = tkinter.PhotoImage('::img::test', master=self.root)200 self.assertEqual(image['file'], '')201 image.configure(file=self.testfile)202 self.assertEqual(image['file'], self.testfile)203 self.assertEqual(image.width(), 16)204 self.assertEqual(image.height(), 16)205 def test_configure_gamma(self):206 image = tkinter.PhotoImage('::img::test', master=self.root)207 self.assertEqual(image['gamma'], '1.0')208 image.configure(gamma=2.0)209 self.assertEqual(image['gamma'], '2.0')210 def test_configure_width_height(self):211 image = tkinter.PhotoImage('::img::test', master=self.root)212 self.assertEqual(image['width'], '0')213 self.assertEqual(image['height'], '0')214 image.configure(width=20)215 image.configure(height=10)216 self.assertEqual(image['width'], '20')217 self.assertEqual(image['height'], '10')218 self.assertEqual(image.width(), 20)219 self.assertEqual(image.height(), 10)220 def test_configure_palette(self):221 image = tkinter.PhotoImage('::img::test', master=self.root)222 self.assertEqual(image['palette'], '')223 image.configure(palette=256)224 self.assertEqual(image['palette'], '256')225 image.configure(palette='3/4/2')226 self.assertEqual(image['palette'], '3/4/2')227 def test_blank(self):228 image = self.create()229 image.blank()230 self.assertEqual(image.width(), 16)231 self.assertEqual(image.height(), 16)232 self.assertEqual(image.get(4, 6), self.colorlist(0, 0, 0))233 def test_copy(self):234 image = self.create()235 image2 = image.copy()236 self.assertEqual(image2.width(), 16)237 self.assertEqual(image2.height(), 16)238 self.assertEqual(image.get(4, 6), image.get(4, 6))239 def test_subsample(self):240 image = self.create()241 image2 = image.subsample(2, 3)242 self.assertEqual(image2.width(), 8)243 self.assertEqual(image2.height(), 6)244 self.assertEqual(image2.get(2, 2), image.get(4, 6))245 image2 = image.subsample(2)246 self.assertEqual(image2.width(), 8)247 self.assertEqual(image2.height(), 8)248 self.assertEqual(image2.get(2, 3), image.get(4, 6))249 def test_zoom(self):250 image = self.create()251 image2 = image.zoom(2, 3)252 self.assertEqual(image2.width(), 32)253 self.assertEqual(image2.height(), 48)254 self.assertEqual(image2.get(8, 18), image.get(4, 6))255 self.assertEqual(image2.get(9, 20), image.get(4, 6))256 image2 = image.zoom(2)257 self.assertEqual(image2.width(), 32)258 self.assertEqual(image2.height(), 32)259 self.assertEqual(image2.get(8, 12), image.get(4, 6))260 self.assertEqual(image2.get(9, 13), image.get(4, 6))261 def test_put(self):262 image = self.create()263 image.put('{red green} {blue yellow}', to=(4, 6))264 self.assertEqual(image.get(4, 6), self.colorlist(255, 0, 0))265 self.assertEqual(image.get(5, 6),266 self.colorlist(0, 128 if tkinter.TkVersion >= 8.6267 else 255, 0))268 self.assertEqual(image.get(4, 7), self.colorlist(0, 0, 255))269 self.assertEqual(image.get(5, 7), self.colorlist(255, 255, 0))270 image.put((('#f00', '#00ff00'), ('#000000fff', '#ffffffff0000')))271 self.assertEqual(image.get(0, 0), self.colorlist(255, 0, 0))272 self.assertEqual(image.get(1, 0), self.colorlist(0, 255, 0))273 self.assertEqual(image.get(0, 1), self.colorlist(0, 0, 255))274 self.assertEqual(image.get(1, 1), self.colorlist(255, 255, 0))275 def test_get(self):276 image = self.create()277 self.assertEqual(image.get(4, 6), self.colorlist(62, 116, 162))278 self.assertEqual(image.get(0, 0), self.colorlist(0, 0, 0))279 self.assertEqual(image.get(15, 15), self.colorlist(0, 0, 0))280 self.assertRaises(tkinter.TclError, image.get, -1, 0)281 self.assertRaises(tkinter.TclError, image.get, 0, -1)282 self.assertRaises(tkinter.TclError, image.get, 16, 15)283 self.assertRaises(tkinter.TclError, image.get, 15, 16)284 def test_write(self):285 image = self.create()286 self.addCleanup(support.unlink, support.TESTFN)287 image.write(support.TESTFN)288 image2 = tkinter.PhotoImage('::img::test2', master=self.root,289 format='ppm',290 file=support.TESTFN)291 self.assertEqual(str(image2), '::img::test2')292 self.assertEqual(image2.type(), 'photo')293 self.assertEqual(image2.width(), 16)294 self.assertEqual(image2.height(), 16)295 self.assertEqual(image2.get(0, 0), image.get(0, 0))296 self.assertEqual(image2.get(15, 8), image.get(15, 8))297 image.write(support.TESTFN, format='gif', from_coords=(4, 6, 6, 9))298 image3 = tkinter.PhotoImage('::img::test3', master=self.root,299 format='gif',300 file=support.TESTFN)301 self.assertEqual(str(image3), '::img::test3')302 self.assertEqual(image3.type(), 'photo')303 self.assertEqual(image3.width(), 2)304 self.assertEqual(image3.height(), 3)305 self.assertEqual(image3.get(0, 0), image.get(4, 6))306 self.assertEqual(image3.get(1, 2), image.get(5, 8))307 def test_transparency(self):308 image = self.create()309 self.assertEqual(image.transparency_get(0, 0), True)310 self.assertEqual(image.transparency_get(4, 6), False)311 image.transparency_set(4, 6, True)312 self.assertEqual(image.transparency_get(4, 6), True)313 image.transparency_set(4, 6, False)314 self.assertEqual(image.transparency_get(4, 6), False)315tests_gui = (MiscTest, DefaultRootTest, BitmapImageTest, PhotoImageTest,)316if __name__ == "__main__":...
ImageDiffSpec.js
Source:ImageDiffSpec.js
1var2 //TODO can roll isNode up into a function if checks get longer3 isNode = typeof module !== 'undefined',4 Canvas = isNode && require('canvas'),5 imagediff = imagediff || require('../js/imagediff.js');6describe('ImageUtils', function() {7 var8 OBJECT = 'object',9 TYPE_CANVAS = isNode ? '[object Canvas]' : '[object HTMLCanvasElement]',10 E_TYPE = { name : 'ImageTypeError', message : 'Submitted object was not an image.' };11 function getContext () {12 var13 canvas = imagediff.createCanvas(),14 context = canvas.getContext('2d');15 return context;16 }17 function newImage () {18 return isNode ? new Canvas.Image() : new Image();19 }20 function toImageDiffEqual (expected) {21 var22 expectedData = expected.data,23 actualData = this.actual.data;24 this.message = function () {25 var26 length = Math.min(expectedData.length, actualData.length),27 examples = '',28 count = 0,29 i;30 for (i = 0; i < length; i++) {31 if (expectedData[i] !== actualData[i]) {32 count++;33 if (count < 10) {34 examples += (examples ? ', ' : '') + 'Expected '+expectedData[i]+' to equal '+actualData[i]+' at '+i;35 }36 }37 }38 return 'Differed in ' + count + ' places. ' + examples;39 }40 return imagediff.equal(this.actual, expected);41 }42 // Creation Testing43 describe('Creation', function () {44 it('should create a canvas', function () {45 var46 canvas = imagediff.createCanvas();47 expect(typeof canvas).toEqual(OBJECT);48 expect(Object.prototype.toString.apply(canvas)).toEqual(TYPE_CANVAS);49 });50 it('should create a canvas with dimensions', function () {51 var52 canvas = imagediff.createCanvas(10, 20);53 expect(typeof canvas).toEqual(OBJECT);54 expect(Object.prototype.toString.apply(canvas)).toEqual(TYPE_CANVAS);55 expect(canvas.width).toEqual(10);56 expect(canvas.height).toEqual(20);57 });58 it('should create an imagedata object', function () {59 var60 imageData = imagediff.createImageData(10, 10);61 expect(typeof imageData).toEqual(OBJECT);62 expect(imageData.width).toBeDefined();63 expect(imageData.height).toBeDefined();64 expect(imageData.data).toBeDefined();65 });66 });67 // Types Testing68 describe('Types', function () {69 // Checking70 describe('Checking', function () {71 var72 image = newImage(),73 canvas = imagediff.createCanvas(),74 context = canvas.getContext('2d'),75 imageData = context.createImageData(30, 30);76 function testType (type, object) {77 return function () {78 expect(imagediff[type](null)).toEqual(false);79 expect(imagediff[type]('')).toEqual(false);80 expect(imagediff[type]({})).toEqual(false);81 expect(imagediff[type](object)).toEqual(true);82 };83 }84 it('should check Image type', testType('isImage', image));85 it('should check Canvas type', testType('isCanvas', canvas));86 it('should check 2DContext type', testType('isContext', context));87 it('should check ImageData type', testType('isImageData', imageData));88 it('should check for any of the image types', function () {89 expect(imagediff.isImageType(null)).toEqual(false);90 expect(imagediff.isImageType('')).toEqual(false);91 expect(imagediff.isImageType({})).toEqual(false);92 expect(imagediff.isImageType(image)).toEqual(true);93 expect(imagediff.isImageType(canvas)).toEqual(true);94 expect(imagediff.isImageType(context)).toEqual(true);95 expect(imagediff.isImageType(imageData)).toEqual(true);96 });97 });98 // Conversion99 describe('Conversion', function () {100 var101 image = newImage(),102 imageData;103 beforeEach(function () {104 this.addMatchers({105 toBeImageData : function () {106 return imagediff.isImageData(this.actual);107 },108 toImageDiffEqual : toImageDiffEqual109 });110 });111 it('should convert Image to ImageData', function () {112 var113 result;114 image.src = 'images/checkmark.png';115 waitsFor(function () {116 return image.complete;117 }, 'image not loaded.', 1000);118 runs(function () {119 var120 canvas = imagediff.createCanvas(image.width, image.height),121 context = canvas.getContext('2d');122 context.drawImage(image, 0, 0);123 imageData = context.getImageData(0, 0, image.width, image.height);124 result = imagediff.toImageData(image);125 expect(result).toBeImageData();126 expect(result).toImageDiffEqual(imageData);127 });128 });129 it('should convert Canvas to ImageData', function () {130 var131 canvas = imagediff.createCanvas(),132 context = canvas.getContext('2d'),133 result;134 canvas.height = image.height;135 canvas.width = image.width;136 context.drawImage(image, 0, 0);137 result = imagediff.toImageData(canvas);138 expect(result).toBeImageData();139 expect(result).toImageDiffEqual(imageData);140 });141 it('should convert Context to ImageData', function () {142 var143 canvas = imagediff.createCanvas(),144 context = canvas.getContext('2d'),145 result = imagediff.toImageData(context);146 expect(result).toBeImageData();147 });148 it('should copy ImageData to new ImageData', function () {149 result = imagediff.toImageData(imageData);150 expect(result).toBeImageData();151 expect(result).toImageDiffEqual(imageData);152 expect(imageData !== result).toBeTruthy();153 });154 it('should fail on non-ImageType', function () {155 expect(function () { imagediff.toImageData() }).toThrow(E_TYPE);156 expect(function () { imagediff.toImageData('') }).toThrow(E_TYPE);157 expect(function () { imagediff.toImageData({}) }).toThrow(E_TYPE);158 });159 });160 });161 // Equals Testing162 describe('Equals', function () {163 var context, a, b;164 beforeEach(function () {165 context = getContext();166 a = context.createImageData(2, 2);167 });168 it('should not be equal for equal ImageData', function () {169 b = context.createImageData(2, 2);170 expect(imagediff.equal(a, b)).toEqual(true);171 });172 it('should not be equal when one ImageData is of different width', function () {173 b = context.createImageData(3, 2);174 expect(imagediff.equal(a, b)).toEqual(false);175 expect(imagediff.equal(b, a)).toEqual(false);176 });177 it('should not be equal when one ImageData is of different height', function () {178 b = context.createImageData(2, 3);179 expect(imagediff.equal(a, b)).toEqual(false);180 expect(imagediff.equal(b, a)).toEqual(false);181 });182 it('should not be equal when one ImageData data array differs', function () {183 b = context.createImageData(2, 2);184 b.data[0] = 100;185 expect(imagediff.equal(a, b)).toEqual(false);186 });187 it('should be equal within optional tolerance', function () {188 b = context.createImageData(2, 2);189 b.data[0] = 100;190 expect(imagediff.equal(a, b, 101)).toEqual(true);191 });192 it('should be equal optional tolerance', function () {193 b = context.createImageData(2, 2);194 b.data[0] = 100;195 expect(imagediff.equal(a, b, 100)).toEqual(true);196 });197 it('should not be equal outside tolerance', function () {198 b = context.createImageData(2, 2);199 b.data[0] = 100;200 expect(imagediff.equal(a, b, 5)).toEqual(false);201 });202 });203 // Diff Testing204 describe('Diff', function () {205 var a, b, c, d;206 beforeEach(function () {207 this.addMatchers({208 toImageDiffEqual : toImageDiffEqual209 });210 });211 describe('Geometry', function () {212 it('should be square, 1x1', function () {213 a = imagediff.createImageData(1, 1),214 b = imagediff.createImageData(1, 1),215 c = imagediff.diff(a, b);216 expect(c.width).toEqual(1);217 expect(c.height).toEqual(1);218 });219 it('should be square, 2x2', function () {220 a = imagediff.createImageData(1, 2),221 b = imagediff.createImageData(2, 1),222 c = imagediff.diff(a, b);223 expect(c.width).toEqual(2);224 expect(c.height).toEqual(2);225 });226 it('should be rectangular, 1x2', function () {227 a = imagediff.createImageData(1, 2),228 b = imagediff.createImageData(1, 1),229 c = imagediff.diff(a, b);230 expect(c.width).toEqual(1);231 expect(c.height).toEqual(2);232 });233 it('should be rectangular, 2x1', function () {234 a = imagediff.createImageData(2, 1),235 b = imagediff.createImageData(1, 1),236 c = imagediff.diff(a, b);237 expect(c.width).toEqual(2);238 expect(c.height).toEqual(1);239 });240 });241 describe('Difference', function () {242 it('should be black', function () {243 a = imagediff.createImageData(1, 1),244 b = imagediff.createImageData(1, 1),245 c = imagediff.diff(a, b);246 d = imagediff.createImageData(1, 1);247 d.data[3] = 255;248 expect(c).toImageDiffEqual(d);249 });250 it('should calculate difference', function () {251 a = imagediff.createImageData(1, 1),252 a.data[1] = 200;253 b = imagediff.createImageData(1, 1),254 b.data[1] = 158;255 c = imagediff.diff(a, b);256 d = imagediff.createImageData(1, 1);257 d.data[1] = 42;258 d.data[3] = 255;259 expect(c).toImageDiffEqual(d);260 });261 it('should center images of unequal size', function () {262 a = imagediff.createImageData(3, 3),263 b = imagediff.createImageData(1, 1),264 b.data[1] = 21;265 c = imagediff.diff(a, b);266 d = imagediff.createImageData(3, 3);267 // 4 * (rowPos * imageWidth + columnPos) + rgbPos268 d.data[4 * (1 * 3 + 1) + 1] = 21;269 // set alpha270 Array.prototype.forEach.call(d.data, function (value, i) {271 if (i % 4 === 3) {272 d.data[i] = 255;273 }274 });275 expect(c).toImageDiffEqual(d);276 });277 it('should optionally align images top left for unequal size', function () {278 a = imagediff.createImageData(3, 3),279 b = imagediff.createImageData(1, 1),280 b.data[1] = 21;281 c = imagediff.diff(a, b, {align: 'top'});282 d = imagediff.createImageData(3, 3);283 d.data[1] = 21;284 // set alpha285 Array.prototype.forEach.call(d.data, function (value, i) {286 if (i % 4 === 3) {287 d.data[i] = 255;288 }289 });290 expect(c).toImageDiffEqual(d);291 });292 });293 /*294 var295 a = imagediff.createImageData(1, 3),296 b = imagediff.createImageData(3, 1),297 c, d;298 a.data[0] = 255;299 a.data[3] = 255;300 a.data[4] = 255;301 a.data[7] = 255;302 a.data[8] = 255;303 a.data[11] = 255;304 b.data[0] = 255;305 b.data[3] = 255;306 b.data[4] = 255;307 b.data[7] = 255;308 b.data[8] = 255;309 b.data[11] = 255;310 */311 });312 // Jasmine Matcher Testing313 describe("jasmine.Matchers", function() {314 var315 imageA = newImage(),316 imageB = newImage(),317 imageC = newImage(),318 env, spec;319 imageA.src = 'images/xmark.png';320 imageB.src = 'images/xmark.png';321 imageC.src = 'images/checkmark.png';322 beforeEach(function() {323 env = new jasmine.Env();324 env.updateInterval = 0;325 var suite = env.describe("suite", function() {326 spec = env.it("spec", function() {327 });328 });329 spyOn(spec, 'addMatcherResult');330 spec.addMatchers(imagediff.jasmine);331 this.addMatchers({332 toPass: function() {333 return lastResult().passed();334 },335 toFail: function() {336 return !lastResult().passed();337 }338 });339 });340 function match(value) {341 return spec.expect(value);342 }343 function lastResult() {344 return spec.addMatcherResult.mostRecentCall.args[0];345 }346 it('toBeImageData', function () {347 var a = imagediff.createImageData(1, 1),348 b = {};349 expect(match(a).toBeImageData()).toPass();350 expect(match(b).toBeImageData()).toFail();351 });352 it('toImageDiffEqual with images', function () {353 waitsFor(function () {354 return imageA.complete && imageB.complete && imageC.complete;355 }, 'image not loaded.', 2000);356 runs(function () {357 expect(match(imageA).toImageDiffEqual(imageB)).toPass();358 expect(match(imageA).toImageDiffEqual(imageC)).toFail();359 expect(function () {360 match(imageA).toImageDiffEqual({});361 }).toThrow(E_TYPE);362 });363 });364 it('toImageDiffEqual with contexts (not a DOM element)', function () {365 var366 a = imagediff.createCanvas(imageA.width, imageA.height).getContext('2d'),367 b = imagediff.createCanvas(imageB.width, imageB.height).getContext('2d'),368 c = imagediff.createCanvas(imageC.width, imageC.height).getContext('2d');369 a.drawImage(imageA, 0, 0);370 b.drawImage(imageB, 0, 0);371 c.drawImage(imageC, 0, 0);372 expect(match(a).toImageDiffEqual(b)).toPass();373 expect(match(a).toImageDiffEqual(c)).toFail();374 expect(function () {375 match(a).toImageDiffEqual({});376 }).toThrow(E_TYPE);377 });378 });379 // Image Output380 describe('Image Output', function () {381 if (!isNode) { return; }382 var383 output = 'images/spec_output.png';384 beforeEach(function () {385 this.addMatchers(imagediff.jasmine)386 });387 afterEach(function () {388 require('fs').unlink(output);389 });390 it('saves an image as a PNG', function () {391 var392 image = newImage(),393 canvas = imagediff.createCanvas(10, 10),394 context = canvas.getContext('2d'),395 a, b;396 context.moveTo(0, 0);397 context.lineTo(10, 10);398 context.strokeStyle = 'rgba(150, 150, 150, .5)';399 context.stroke();400 a = context.getImageData(0, 0, 10, 10);401 imagediff.imageDataToPNG(a, output, function () {402 image.src = output;403 });404 waitsFor(function () {405 return image.complete;406 }, 'image not loaded.', 2000);407 runs(function () {408 b = imagediff.toImageData(image);409 expect(b).toBeImageData();410 expect(canvas).toImageDiffEqual(b, 10);411 });412 });413 });414 // Compatibility Testing415 describe('Compatibility', function () {416 var417 fn = Function,418 global = (fn('return this;')()), // Get the global object419 that = imagediff,420 reference;421 afterEach(function () {422 global.imagediff = that;423 });424 it('should remove imagediff from global space', function () {425 imagediff.noConflict();426 if (!isNode) {427 expect(imagediff === that).toEqual(false);428 expect(global.imagediff === that).toEqual(false);429 }430 });431 it('should return imagediff', function () {432 reference = imagediff.noConflict();433 expect(reference === that).toEqual(true);434 });435 });...
image_utils.py
Source:image_utils.py
...27 PIL.Image.Image, np.ndarray, "torch.Tensor", List[PIL.Image.Image], List[np.ndarray], List["torch.Tensor"] # noqa28]29def is_torch_tensor(obj):30 return _is_torch(obj) if is_torch_available() else False31def load_image(image: Union[str, "PIL.Image.Image"]) -> "PIL.Image.Image":32 """33 Loads `image` to a PIL Image.34 Args:35 image (`str` or `PIL.Image.Image`):36 The image to convert to the PIL Image format.37 Returns:38 `PIL.Image.Image`: A PIL Image.39 """40 if isinstance(image, str):41 if image.startswith("http://") or image.startswith("https://"):42 # We need to actually check for a real protocol, otherwise it's impossible to use a local file43 # like http_huggingface_co.png44 image = PIL.Image.open(requests.get(image, stream=True).raw)45 elif os.path.isfile(image):46 image = PIL.Image.open(image)47 else:48 raise ValueError(49 f"Incorrect path or url, URLs must start with `http://` or `https://`, and {image} is not a valid path"50 )51 elif isinstance(image, PIL.Image.Image):52 image = image53 else:54 raise ValueError(55 "Incorrect format used for image. Should be an url linking to an image, a local path, or a PIL image."56 )57 image = PIL.ImageOps.exif_transpose(image)58 image = image.convert("RGB")59 return image60# In the future we can add a TF implementation here when we have TF models.61class ImageFeatureExtractionMixin:62 """63 Mixin that contain utilities for preparing image features.64 """65 def _ensure_format_supported(self, image):66 if not isinstance(image, (PIL.Image.Image, np.ndarray)) and not is_torch_tensor(image):67 raise ValueError(68 f"Got type {type(image)} which is not supported, only `PIL.Image.Image`, `np.array` and "69 "`torch.Tensor` are."70 )71 def to_pil_image(self, image, rescale=None):72 """73 Converts `image` to a PIL Image. Optionally rescales it and puts the channel dimension back as the last74 axis if needed.75 Args:76 image (`PIL.Image.Image` or `numpy.ndarray` or `torch.Tensor`):77 The image to convert to the PIL Image format.78 rescale (`bool`, *optional*):79 Whether or not to apply the scaling factor (to make pixel values integers between 0 and 255). Will80 default to `True` if the image type is a floating type, `False` otherwise.81 """82 self._ensure_format_supported(image)83 if is_torch_tensor(image):84 image = image.numpy()85 if isinstance(image, np.ndarray):86 if rescale is None:87 # rescale default to the array being of floating type.88 rescale = isinstance(image.flat[0], np.floating)89 # If the channel as been moved to first dim, we put it back at the end.90 if image.ndim == 3 and image.shape[0] in [1, 3]:91 image = image.transpose(1, 2, 0)92 if rescale:93 image = image * 25594 image = image.astype(np.uint8)95 return PIL.Image.fromarray(image)96 return image97 def to_numpy_array(self, image, rescale=None, channel_first=True):98 """99 Converts `image` to a numpy array. Optionally rescales it and puts the channel dimension as the first100 dimension.101 Args:102 image (`PIL.Image.Image` or `np.ndarray` or `torch.Tensor`):103 The image to convert to a NumPy array.104 rescale (`bool`, *optional*):105 Whether or not to apply the scaling factor (to make pixel values floats between 0. and 1.). Will106 default to `True` if the image is a PIL Image or an array/tensor of integers, `False`107 otherwise.108 channel_first (`bool`, *optional*, defaults to `True`):109 Whether or not to permute the dimensions of the image to put the channel dimension first.110 """111 self._ensure_format_supported(image)112 if isinstance(image, PIL.Image.Image):113 image = np.array(image)114 if is_torch_tensor(image):115 image = image.numpy()116 if rescale is None:117 rescale = isinstance(image.flat[0], np.integer)118 if rescale:119 image = image.astype(np.float32) / 255.0120 if channel_first and image.ndim == 3:121 image = image.transpose(2, 0, 1)122 return image123 def normalize(self, image, mean, std):124 """125 Normalizes `image` with `mean` and `std`. Note that this will trigger a conversion of126 `image` to a NumPy array if it's a PIL Image.127 Args:128 image (`PIL.Image.Image` or `np.ndarray` or `torch.Tensor`):129 The image to normalize.130 mean (`List[float]` or `np.ndarray` or `torch.Tensor`):131 The mean (per channel) to use for normalization.132 std (`List[float]` or `np.ndarray` or `torch.Tensor`):133 The standard deviation (per channel) to use for normalization.134 """135 self._ensure_format_supported(image)136 if isinstance(image, PIL.Image.Image):137 image = self.to_numpy_array(image)138 if isinstance(image, np.ndarray):139 if not isinstance(mean, np.ndarray):140 mean = np.array(mean).astype(image.dtype)141 if not isinstance(std, np.ndarray):142 std = np.array(std).astype(image.dtype)143 elif is_torch_tensor(image):144 import torch145 if not isinstance(mean, torch.Tensor):146 mean = torch.tensor(mean)147 if not isinstance(std, torch.Tensor):148 std = torch.tensor(std)149 if image.ndim == 3 and image.shape[0] in [1, 3]:150 return (image - mean[:, None, None]) / std[:, None, None]151 else:152 return (image - mean) / std153 def resize(self, image, size, resample=PIL.Image.BILINEAR):154 """155 Resizes `image`. Note that this will trigger a conversion of `image` to a PIL Image.156 Args:157 image (`PIL.Image.Image` or `np.ndarray` or `torch.Tensor`):158 The image to resize.159 size (`int` or `Tuple[int, int]`):160 The size to use for resizing the image.161 resample (`int`, *optional*, defaults to `PIL.Image.BILINEAR`):162 The filter to user for resampling.163 """164 self._ensure_format_supported(image)165 if isinstance(size, int):166 size = (size, size)167 elif isinstance(size, list):168 size = tuple(size)169 if not isinstance(image, PIL.Image.Image):170 image = self.to_pil_image(image)171 return image.resize(size, resample=resample)172 def center_crop(self, image, size):173 """174 Crops `image` to the given size using a center crop. Note that if the image is too small to be cropped to175 the size given, it will be padded (so the returned result has the size asked).176 Args:177 image (`PIL.Image.Image` or `np.ndarray` or `torch.Tensor`):178 The image to resize.179 size (`int` or `Tuple[int, int]`):180 The size to which crop the image.181 """182 self._ensure_format_supported(image)183 if not isinstance(size, tuple):184 size = (size, size)...
zoom.js
Source:zoom.js
1/**2 * Copyright © 2013-2017 Magento, Inc. All rights reserved.3 * See COPYING.txt for license details.4 */5/*jshint browser:true jquery:true expr:true*/6define([7 "jquery",8 "jquery/ui"9], function($){10 $.widget('mage.zoom', {11 options: {12 sliderSpeed: 1013 },14 _create: function() {15 this.sliderMax = $(this.options.sliderSelector).width();16 this.image = this.element;17 this.imageWidth = this.image.width();18 this.imageHeight = this.image.height();19 this.imageParent = this.image.parent();20 this.imageParentWidth = this.imageParent.width();21 this.imageParentHeight = this.imageParent.height();22 this.showFullImage = false;23 if (!this._isZoomable()) {24 return;25 }26 this._initialResize();27 // Slide slider to zoom in or out the picture28 this.slider = $(this.options.sliderSelector).slider({29 value: 0,30 min: 0,31 max: this.sliderMax,32 slide: $.proxy(function(event, ui) {33 this._zoom(ui.value, this.sliderMax);34 }, this),35 change: $.proxy(function(event, ui) {36 this._zoom(ui.value, this.sliderMax);37 }, this)38 });39 // Mousedown on zoom in icon to zoom in picture40 $(this.options.zoomInSelector).on('mousedown', $.proxy(function() {41 this.intervalId = setInterval($.proxy(function() {42 this.slider.slider('value', this.slider.slider('value') + 1);43 }, this), this.options.sliderSpeed);44 }, this)).on('mouseup mouseleave', $.proxy(function() {45 clearInterval(this.intervalId);46 }, this));47 // Mousedown on zoom out icon to zoom out picture48 $(this.options.zoomOutSelector).on('mousedown', $.proxy(function() {49 this.intervalId = setInterval($.proxy(function() {50 this.slider.slider('value', this.slider.slider('value') - 1);51 }, this), this.options.sliderSpeed);52 }, this)).on('mouseup mouseleave', $.proxy(function() {53 clearInterval(this.intervalId);54 }, this));55 // Double-click image to see full picture56 this.element.on('dblclick', $.proxy(function() {57 this.showFullImage = !this.showFullImage;58 var ratio = this.showFullImage ? this.sliderMax : this.slider.slider('value');59 this._zoom(ratio, this.sliderMax);60 if (this.showFullImage) {61 $(this.options.sliderSelector).hide();62 $(this.options.zoomInSelector).hide();63 $(this.options.zoomOutSelector).hide();64 this.imageParent.css({'overflow': 'visible', 'zIndex': '1000'});65 } else {66 $(this.options.sliderSelector).show();67 $(this.options.zoomInSelector).show();68 $(this.options.zoomOutSelector).show();69 this.imageParent.css({'overflow': 'hidden', 'zIndex': '9'});70 }71 }, this));72 // Window resize will change offset for draggable73 $(window).resize(this._draggableImage());74 },75 /**76 * If image dimension is smaller than parent container, disable zoom77 * @private78 */79 _isZoomable: function() {80 if (this.imageWidth <= this.imageParentWidth && this.imageHeight <= this.imageParentHeight) {81 $(this.options.sliderSelector).parent().hide();82 $(this.options.zoomNoticeSelector).hide();83 return false;84 }85 return true;86 },87 /**88 * Resize image to fit parent container and set initial image dimension89 * @private90 */91 _initialResize: function() {92 if (this.imageWidth > this.imageHeight) {93 this.ceilingZoom = this.imageWidth / this.imageParentWidth;94 this.image.width(this.imageParentWidth);95 this.image.css('top', ((this.imageParentHeight - this.image.height()) / 2) + 'px');96 } else {97 this.ceilingZoom = this.imageHeight / this.imageParentHeight;98 this.image.height(this.imageParentHeight);99 this.image.css('left', ((this.imageParentWidth - this.image.width()) / 2) + 'px');100 }101 // Remember Image original position102 this.imageInitTop = this.image.position().top;103 this.imageInitLeft = this.image.position().left;104 },105 /**106 * Make Image draggable inside parent container dimension107 * @private108 */109 _draggableImage: function() {110 var topX = this.image.offset().left,111 topY = this.image.offset().top,112 bottomX = this.image.offset().left,113 bottomY = this.image.offset().top;114 // Calculate x offset if image width is greater than image container width115 if (this.image.width() > this.imageParentWidth) {116 topX = this.image.width() - (this.imageParent.offset().left -117 this.image.offset().left) - this.imageParentWidth;118 topX = this.image.offset().left - topX;119 bottomX = this.imageParent.offset().left - this.image.offset().left;120 bottomX = this.image.offset().left + bottomX;121 }122 // Calculate y offset if image height is greater than image container height123 if (this.image.height() > this.imageParentHeight) {124 topY = this.image.height() - (this.imageParent.offset().top -125 this.image.offset().top) - this.imageParentHeight;126 topY = this.image.offset().top - topY;127 bottomY = this.imageParent.offset().top - this.image.offset().top;128 bottomY = this.image.offset().top + bottomY;129 }130 // containment field is used because image is larger than parent container131 this.element.draggable({132 containment: [topX, topY, bottomX, bottomY],133 scroll: false134 });135 },136 /**137 * Resize image based on slider position138 * @param sliderPosition - current slider position (0 to slider track max length)139 * @param sliderLength - slider track max length140 * @private141 */142 _zoom: function(sliderPosition, sliderLength) {143 var ratio = sliderPosition / sliderLength;144 ratio = ratio > 1 ? 1 : ratio;145 var imageOldLeft = this.image.position().left;146 var imageOldTop = this.image.position().top;147 var imageOldWidth = this.image.width();148 var imageOldHeight = this.image.height();149 var overSize = (this.imageWidth > this.imageParentWidth || this.imageHeight > this.imageParentHeight);150 var floorZoom = 1;151 var imageZoom = floorZoom + (ratio * (this.ceilingZoom - floorZoom));152 // Zoomed image is larger than container, and resize image based on zoom ratio153 if (overSize) {154 this.imageWidth > this.imageHeight ? this.image.width(imageZoom * this.imageParentWidth) :155 this.image.height(imageZoom * this.imageParentHeight);156 } else {157 $(this.options.sliderSelector).hide();158 }159 // Position zoomed image properly160 var imageNewLeft = imageOldLeft - (this.image.width() - imageOldWidth) / 2;161 var imageNewTop = imageOldTop - (this.image.height() - imageOldHeight) / 2;162 // Image can't be positioned more left than original left163 if (imageNewLeft > this.imageInitLeft || this.image.width() < this.imageParentWidth) {164 imageNewLeft = this.imageInitLeft;165 }166 // Image can't be positioned more right than the difference between parent width and image current width167 if (Math.abs(imageNewLeft) > Math.abs(this.imageParentWidth - this.image.width())) {168 imageNewLeft = this.imageParentWidth - this.image.width();169 }170 // Image can't be positioned more down than original top171 if (imageNewTop > this.imageInitTop || this.image.height() < this.imageParentHeight) {172 imageNewTop = this.imageInitTop;173 }174 // Image can't be positioned more top than the difference between parent height and image current height175 if (Math.abs(imageNewTop) > Math.abs(this.imageParentHeight - this.image.height())) {176 imageNewTop = this.imageParentHeight - this.image.height();177 }178 this.image.css({'left': imageNewLeft + 'px', 'top': imageNewTop + 'px'});179 // Because image size and position changed, we need to recalculate draggable image containment180 this._draggableImage();181 }182 });...
image_maper.js
Source:image_maper.js
1/////////////////////////////////////////////////////////////2//3// pgAdmin 4 - PostgreSQL Tools4//5// Copyright (C) 2013 - 2021, The pgAdmin Development Team6// This software is released under the PostgreSQL Licence7//8//////////////////////////////////////////////////////////////9/*10 * A map which is used to fetch the image to be drawn and11 * text which will appear below it12 */13let imageMapper = {14 'Aggregate': {15 'image': 'ex_aggregate.svg',16 'image_text': 'Aggregate',17 },18 'Append': {19 'image': 'ex_append.svg',20 'image_text': 'Append',21 },22 'Bitmap Index Scan': function(data) {23 return {24 'image': 'ex_bmp_index.svg',25 'image_text': data['Index Name'],26 };27 },28 'Bitmap Heap Scan': function(data) {29 return {30 'image': 'ex_bmp_heap.svg',31 'image_text': data['Relation Name'],32 };33 },34 'BitmapAnd': {35 'image': 'ex_bmp_and.svg',36 'image_text': 'Bitmap AND',37 },38 'BitmapOr': {39 'image': 'ex_bmp_or.svg',40 'image_text': 'Bitmap OR',41 },42 'CTE Scan': {43 'image': 'ex_cte_scan.svg',44 'image_text': 'CTE Scan',45 },46 'Function Scan': {47 'image': 'ex_result.svg',48 'image_text': 'Function Scan',49 },50 'Foreign Scan': {51 'image': 'ex_foreign_scan.svg',52 'image_text': 'Foreign Scan',53 },54 'Gather': {55 'image': 'ex_gather_motion.svg',56 'image_text': 'Gather',57 },58 'Gather Merge': {59 'image': 'ex_gather_merge.svg',60 'image_text': 'Gather Merge',61 },62 'Group': {63 'image': 'ex_group.svg',64 'image_text': 'Group',65 },66 'GroupAggregate': {67 'image': 'ex_aggregate.svg',68 'image_text': 'Group Aggregate',69 },70 'Hash': {71 'image': 'ex_hash.svg',72 'image_text': 'Hash',73 },74 'Hash Join': function(data) {75 if (!data['Join Type']) return {76 'image': 'ex_join.svg',77 'image_text': 'Join',78 };79 switch (data['Join Type']) {80 case 'Anti':81 return {82 'image': 'ex_hash_anti_join.svg',83 'image_text': 'Hash Anti Join',84 };85 case 'Semi':86 return {87 'image': 'ex_hash_semi_join.svg',88 'image_text': 'Hash Semi Join',89 };90 default:91 return {92 'image': 'ex_hash.svg',93 'image_text': String('Hash ' + data['Join Type'] + ' Join'),94 };95 }96 },97 'HashAggregate': {98 'image': 'ex_aggregate.svg',99 'image_text': 'Hash Aggregate',100 },101 'Index Only Scan': function(data) {102 return {103 'image': 'ex_index_only_scan.svg',104 'image_text': data['Index Name'],105 };106 },107 'Index Scan': function(data) {108 return {109 'image': 'ex_index_scan.svg',110 'image_text': data['Index Name'],111 };112 },113 'Index Scan Backword': {114 'image': 'ex_index_scan.svg',115 'image_text': 'Index Backward Scan',116 },117 'Limit': {118 'image': 'ex_limit.svg',119 'image_text': 'Limit',120 },121 'LockRows': {122 'image': 'ex_lock_rows.svg',123 'image_text': 'Lock Rows',124 },125 'Materialize': {126 'image': 'ex_materialize.svg',127 'image_text': 'Materialize',128 },129 'Merge Append': {130 'image': 'ex_merge_append.svg',131 'image_text': 'Merge Append',132 },133 'Merge Join': function(data) {134 switch (data['Join Type']) {135 case 'Anti':136 return {137 'image': 'ex_merge_anti_join.svg',138 'image_text': 'Merge Anti Join',139 };140 case 'Semi':141 return {142 'image': 'ex_merge_semi_join.svg',143 'image_text': 'Merge Semi Join',144 };145 default:146 return {147 'image': 'ex_merge.svg',148 'image_text': String('Merge ' + data['Join Type'] + ' Join'),149 };150 }151 },152 'ModifyTable': function(data) {153 switch (data['Operation']) {154 case 'Insert':155 return {156 'image': 'ex_insert.svg',157 'image_text': 'Insert',158 };159 case 'Update':160 return {161 'image': 'ex_update.svg',162 'image_text': 'Update',163 };164 case 'Delete':165 return {166 'image': 'ex_delete.svg',167 'image_text': 'Delete',168 };169 }170 },171 'Named Tuplestore Scan': {172 'image': 'ex_named_tuplestore_scan.svg',173 'image_text': 'Named Tuplestore Scan',174 },175 'Nested Loop': function(data) {176 switch (data['Join Type']) {177 case 'Anti':178 return {179 'image': 'ex_nested_loop_anti_join.svg',180 'image_text': 'Nested Loop Anti Join',181 };182 case 'Semi':183 return {184 'image': 'ex_nested_loop_semi_join.svg',185 'image_text': 'Nested Loop Semi Join',186 };187 default:188 return {189 'image': 'ex_nested.svg',190 'image_text': 'Nested Loop ' + data['Join Type'] + ' Join',191 };192 }193 },194 'ProjectSet': {195 'image': 'ex_projectset.svg',196 'image_text': 'ProjectSet',197 },198 'Recursive Union': {199 'image': 'ex_recursive_union.svg',200 'image_text': 'Recursive Union',201 },202 'Result': {203 'image': 'ex_result.svg',204 'image_text': 'Result',205 },206 'Sample Scan': {207 'image': 'ex_scan.svg',208 'image_text': 'Sample Scan',209 },210 'Scan': {211 'image': 'ex_scan.svg',212 'image_text': 'Scan',213 },214 'Seek': {215 'image': 'ex_seek.svg',216 'image_text': 'Seek',217 },218 'SetOp': function(data) {219 let strategy = data['Strategy'],220 command = data['Command'];221 if (strategy == 'Hashed') {222 if (command.startsWith('Intersect')) {223 if (command == 'Intersect All')224 return {225 'image': 'ex_hash_setop_intersect_all.svg',226 'image_text': 'Hashed Intersect All',227 };228 return {229 'image': 'ex_hash_setop_intersect.svg',230 'image_text': 'Hashed Intersect',231 };232 } else if (command.startsWith('Except')) {233 if (command == 'Except All')234 return {235 'image': 'ex_hash_setop_except_all.svg',236 'image_text': 'Hashed Except All',237 };238 return {239 'image': 'ex_hash_setop_except.svg',240 'image_text': 'Hash Except',241 };242 }243 return {244 'image': 'ex_hash_setop_unknown.svg',245 'image_text': 'Hashed SetOp Unknown',246 };247 }248 return {249 'image': 'ex_setop.svg',250 'image_text': 'SetOp',251 };252 },253 'Seq Scan': function(data) {254 return {255 'image': 'ex_scan.svg',256 'image_text': data['Relation Name'],257 };258 },259 'Subquery Scan': {260 'image': 'ex_subplan.svg',261 'image_text': 'SubQuery Scan',262 },263 'Sort': {264 'image': 'ex_sort.svg',265 'image_text': 'Sort',266 },267 'Tid Scan': {268 'image': 'ex_tid_scan.svg',269 'image_text': 'Tid Scan',270 },271 'Table Function Scan': {272 'image': 'ex_table_func_scan.svg',273 'image_text': 'Table Function Scan',274 },275 'Unique': {276 'image': 'ex_unique.svg',277 'image_text': 'Unique',278 },279 'Values Scan': {280 'image': 'ex_values_scan.svg',281 'image_text': 'Values Scan',282 },283 'WindowAgg': {284 'image': 'ex_window_aggregate.svg',285 'image_text': 'Window Aggregate',286 },287 'WorkTable Scan': {288 'image': 'ex_worktable_scan.svg',289 'image_text': 'WorkTable Scan',290 },291 'Undefined': {292 'image': 'ex_unknown.svg',293 'image_text': 'Undefined',294 },295};...
Using AI Code Generation
1const differencify = require('differencify')2const { image } = differencify3const { resemblejs } = differencify4const { pixelmatch } = differencify5const { jimp } = differencify6const { pixelmatch } = differencify7const { jimp } = differencify8const { pixelmatch } = differencify9const { jimp } = differencify10const { pixelmatch } = differencify11const { jimp } = differencify12const { pixelmatch } = differencify13const { jimp } = differencify14const { pixelmatch } = differencify15const { jimp } = differencify16const { pixelmatch } = differencify17const { jimp } = differencify18const { pixelmatch } = differencify19const { jimp } = differencify20const { pixelmatch } = differencify21const { jimp } = differencify22const { pixelmatch } = differencify23const { jimp } = differencify24const { pixel
Using AI Code Generation
1var differencify = require('differencify');2var differencify = new differencify();3var path = require('path');4var image = differencify.image;5var expect = require('chai').expect;6describe('Test Case', function() {7 it('Test Case 1', function() {8 var image1 = path.join(__dirname, 'images', 'image1.png');9 var image2 = path.join(__dirname, 'images', 'image2.png');10 var result = image(image1, image2);11 expect(result).to.be.true;12 });13});14var differencify = require('differencify');15var differencify = new differencify();16var image = differencify.image;17var image1 = 'image1.png';18var image2 = 'image2.png';19var result = image(image1, image2);20console.log(result);21var differencify = require('differencify');22var differencify = new differencify();23var image = differencify.image;24var image1 = 'image1.png';25var image2 = 'image2.png';26var result = image(image1, image2);27console.log(result);
Using AI Code Generation
1const differencify = require('differencify');2const options = {3 image: {4 formatImageName: '{tag}-{logName}-{width}x{height}',5 }6}7differencify.init(browser, options);8describe('Test', () => {9 it('should work', async () => {10 await browser.saveElement(await $('body'), 'body');11 await expect(await $('body')).toMatchElement('body');12 });13});14exports.config = {15 capabilities: [{16 }],17 reporters: ['spec', ['junit', {18 }], ['allure', {19 }]],20 mochaOpts: {21 },22 beforeSession: function (config, capabilities, specs) {23 require('ts-node').register({ files: true });24 },25 before: function (capabilities, specs) {26 global.expect = require('chai').expect;27 },28 afterTest: function (test, context, { error, result, duration, passed, retries }) {29 if (error) {30 browser.takeScreenshot();31 }32 }33};
Using AI Code Generation
1const differencify = require("differencify");2const config = require("./config.json");3const puppeteer = require("puppeteer");4const { expect } = require("chai");5const { diff } = require("deep-diff");6const fs = require("fs");7async function run() {8 const browser = await puppeteer.launch();9 const page = await browser.newPage();10 await page.screenshot({ path: "test.png" });11 await browser.close();12}13run().then(() => {14 const image = differencify.image;15 const test = image("test.png");16 test.toMatchImageSnapshot("test.png");17});18{19}20{21 "scripts": {22 },23 "dependencies": {24 },25 "devDependencies": {26 }27}
Using AI Code Generation
1const differencify = require('differencify')2const opts = {3 image: {4 diff: {5 blockOut: { x: 0, y: 0, width: 0, height: 0 },6 blockOut: { x: 0, y: 0, width: 0, height: 0 },7 output: {8 }9 }10 }11}12differencify.init(opts)13differencify.setConfig(opts)14### `init(opts)`15### `setConfig(opts)`16### `compare(opts)`17const opts = {18 image: {19 diff: {20 blockOut: { x: 0, y: 0, width: 0, height: 0 },21 blockOut: { x: 0, y: 0, width: 0, height: 0 },
Using AI Code Generation
1var differencify = require('differencify');2var image = differencify.image;3var fs = require('fs');4var screenshot = fs.readFileSync('screenshot.png');5var baseline = fs.readFileSync('baseline.png');6image(screenshot, baseline, function (err, result) {7 console.log(result);8});9image('screenshot.png', 'baseline.png', function (err, result) {10 console.log(result);11});12image('screenshot.png', 'baseline.png', {threshold: 0.1}, function (err, result) {13 console.log(result);14});15image('screenshot.png', 'baseline.png', {threshold: 0.1}, function (err, result) {16 console.log(result);17});18image('screenshot.png', 'baseline.png', {threshold: 0.1, output: 'diff.png'}, function (err, result) {19 console.log(result);20});21image('screenshot.png', 'baseline.png', {threshold: 0.1, output: 'diff.png', outputDiff: true}, function (err, result) {22 console.log(result);23});24image('screenshot.png', 'baseline.png', {threshold: 0.1, outputDiff: true}, function (err, result) {25 console.log(result);26});27image('screenshot.png', 'baseline.png', {threshold: 0.1, outputDiff: true, outputMask: true}, function (err, result) {28 console.log(result);29});30image('screenshot.png', 'baseline.png', {threshold: 0.1, outputDiff: true, outputMask: true, outputDiffMask: true}, function (err, result) {31 console.log(result);32});33image('screenshot.png', 'baseline.png', {threshold: 0.1, outputDiff:
Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!