Created
September 14, 2014 04:21
-
-
Save zhangyuan/5c71deea1402c206426c to your computer and use it in GitHub Desktop.
encode image with base64 algorithm from image src
This file contains hidden or 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
function getBase64Image(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,/, ""); | |
} | |
var dataURL; | |
var src = "http://example.com/some_image.png"; | |
var image = new Image(); | |
image.src = src; | |
image.onload = function() { | |
dataURL = getBase64Image(image); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment