Created
March 8, 2019 09:47
-
-
Save pete-otaqui/eb31b743201909bc6731f4f850cc0213 to your computer and use it in GitHub Desktop.
Convert Image to Base 64 WebDriver JS and Node style
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// This runs in a browser, | |
// it's usable with WebDriver as an injected script | |
function convertImagetoBase64(selector) { | |
const image = document.querySelector(selector); | |
const canvas = document.createElement("canvas"); | |
const context = canvas.getContext("2d"); | |
const { width, height } = image; | |
canvas.width = width; | |
canvas.height = height; | |
context.drawImage(image, 0, 0, width, height); | |
const base64String = canvas.toDataURL(); | |
return base64String; | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// This runs in Node | |
const fs = require("fs"); | |
function saveBase64URLAsFile(base64URL, filename) { | |
return new Promise((resolve, reject) => { | |
const base64Data = dataURL.replace(/^data:image\/png;base64,/, ""); | |
const binaryData = Buffer.from(base64Data, "base64").toString("binary"); | |
fs.writeFile(filename, binaryData, "binary", err => { | |
if (err) { | |
reject(err); | |
} else { | |
resolve(); | |
} | |
}); | |
}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment