Last active
July 1, 2018 09:25
-
-
Save JokingChicken/74226c5cc0ba5f159af439efdaa2c7bd to your computer and use it in GitHub Desktop.
encode and decode img from base64
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
/* | |
* creator: Danj (https://github.com/DanBrothers) | |
* description: encode and decode img from base64 | |
* license: MIT, please link to this if you copy (thanks) | |
* | |
* usage: | |
var base64 = getBase64FromImage(document.getElementById("imageid")); | |
var img = getImageFromBase64(base64); | |
*/ | |
function getBase64FromImage(img) { | |
var canvas = document.createElement("canvas"); | |
canvas.width = img.width; | |
canvas.height = img.height; | |
var ctx = canvas.getContext("2d"); | |
ctx.drawImage(img, 0, 0); | |
var dataURL = canvas.toDataURL("image/png"); | |
return dataURL.replace(/^data:image\/(png|jpg);base64,/, ""); | |
} | |
function getImageFromBase64(base64) { | |
var image = new Image(); | |
image.src = 'data:image/png;base64,' + base64; | |
return image; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment