HTML
<img id="imageid" src="https://www.google.de/images/srpr/logo11w.png">
JavaScript
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\/?[A-z]*;base64,/);
}
var base64 = getBase64Image(document.getElementById("imageid"));
Special thanks to @Md. Hasan Mahmud for providing an improved regex that works with any image mime type in my comments!
This method requires the canvas element, which is perfectly supported.
- The MDN reference of
HTMLCanvasElement.toDataURL(). - And the official W3C documentation.
HTML
<img id="imageid" src="https://www.google.de/images/srpr/logo11w.png">
JavaScript
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\/?[A-z]*;base64,/);
}
var base64 = getBase64Image(document.getElementById("imageid"));
Special thanks to @Md. Hasan Mahmud for providing an improved regex that works with any image mime type in my comments!
This method requires the canvas element, which is perfectly supported.
- The MDN reference of
HTMLCanvasElement.toDataURL(). - And the official W3C documentation.
View this answer: https://stackoverflow.com/a/20285053/5065874 by @HaNdTriX
Basically, he implemented this function:
function toDataUrl(url, callback) {
var xhr = new XMLHttpRequest();
xhr.onload = function() {
var reader = new FileReader();
reader.onloadend = function() {
callback(reader.result);
}
reader.readAsDataURL(xhr.response);
};
xhr.open('GET', url);
xhr.responseType = 'blob';
xhr.send();
}
And in your case, you can use it like this:
toDataUrl(imagepath, function(myBase64) {
console.log(myBase64); // myBase64 is the base64 string
});
How can I convert an image into Base64 string using JavaScript? - Stack Overflow
Is there a way to convert the s3 image URL to base64 in nodejs
Is there a way to convert the s3 image URL to base64.?
You don’t want to convert the URL to base64, how would that help? You want to convert the image content to base64.
More on reddit.comHow to change base64 svg+xml image color ?
a couple pieces of advice:
you don't need to use all this URI encoding. it makes it a lot harder to edit directly. you only need to remove any special characters like # and turn all quotations into apostrophes: " to '
at that point it will register correctly in CSS. since you only have two colors (#000000 and the blue you want to get rid of) the solution is easy. you just use "black" instead of "#000000" and "context-stroke" instead of the blue. then, you can use CSS rules to set the stroke color instead of defining the stroke color directly within the SVG code. I did it for you:
element {
list-style-image: url("data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 72 72'><circle cx='36' cy='36' r='33' stroke='black' stroke-opacity='.15' fill='none' stroke-miterlimit='10' stroke-width='5'/><path d='M14.3 60.9A33 33 0 0136 3' stroke='context-stroke' fill='none' stroke-miterlimit='10' stroke-width='5'/></svg>");
-moz-context-properties: fill, stroke, fill-opacity, stroke-opacity !important;
stroke: #FF0000;
}the -moz-context-properties rule is the key there. once you set that, you can use rules like "stroke:" or "fill-opacity:" and those rules will define whatever you set within the SVG code as stroke='context-stroke' or fill-opacity='context-fill-opacity'. in other words, instead of writing stroke='#FF0000' you're defining the stroke as a variable and then setting the variable from outside of the SVG's scope, via a CSS rule.
edit: by the way, just so you're aware, what you pasted was not encoded in base64. that was utf8 with URI percent encoding, meaning all the special characters are replaced with percent codes e.g. # => %23. if it actually was base64, then it wouldn't work, because your data link says "data:image/svg+xml;utf8", which is where the character encoding is defined. if it's set wrong then it won't work at all. if you want to use base64 instead, then you have to write "data:image/svg+xml;base64". but for this kind of application i don't think there's much reason to use base64. unless the illustration has a whole lot of colors, it's better to just make the whole thing human-readable so you can edit it directly. and even if it does require a lot of colors, you only need to replace the quotations and # symbols. so i almost never use base64 encoding in CSS. if you really need to embed a bunch of unique colors in the SVG code, then just write fill='%23FF0000' and leave everything else alone. the way yours is encoded is more like the way URI queries are encoded in some database programs, where even the spaces are replaced with percent codes, which is obviously not necessary for embedding SVG in data links for CSS.
More on reddit.com
» npm install image-to-base64
There are multiple approaches you can choose from:
1. Approach: FileReader
Load the image as blob via XMLHttpRequest and use the FileReader API (readAsDataURL()) to convert it to a dataURL:
function toDataURL(url, callback) {
var xhr = new XMLHttpRequest();
xhr.onload = function() {
var reader = new FileReader();
reader.onloadend = function() {
callback(reader.result);
}
reader.readAsDataURL(xhr.response);
};
xhr.open('GET', url);
xhr.responseType = 'blob';
xhr.send();
}
toDataURL('https://www.gravatar.com/avatar/d50c83cc0c6523b4d3f6085295c953e0', function(dataUrl) {
console.log('RESULT:', dataUrl)
})
This code example could also be implemented using the WHATWG fetch API:
const toDataURL = url => fetch(url)
.then(response => response.blob())
.then(blob => new Promise((resolve, reject) => {
const reader = new FileReader()
reader.onloadend = () => resolve(reader.result)
reader.onerror = reject
reader.readAsDataURL(blob)
}))
toDataURL('https://www.gravatar.com/avatar/d50c83cc0c6523b4d3f6085295c953e0')
.then(dataUrl => {
console.log('RESULT:', dataUrl)
})
These approaches:
- have better compression
- work for other file types as well
Browser Support:
- http://caniuse.com/#feat=filereader
- http://caniuse.com/#feat=fetch
Tip: To convert local files, you can use live-server. Once started on the folder that contains the picture to transform, open the url in browser and using developer console you can convert the image to base 64.
2. Approach: Canvas (for legacy browsers)
Load the image into an Image-Object, paint it to a nontainted canvas and convert the canvas back to a dataURL.
function toDataURL(src, callback, outputFormat) {
var img = new Image();
img.crossOrigin = 'Anonymous';
img.onload = function() {
var canvas = document.createElement('CANVAS');
var ctx = canvas.getContext('2d');
var dataURL;
canvas.height = this.naturalHeight;
canvas.width = this.naturalWidth;
ctx.drawImage(this, 0, 0);
dataURL = canvas.toDataURL(outputFormat);
callback(dataURL);
};
img.src = src;
if (img.complete || img.complete === undefined) {
img.src = "data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///ywAAAAAAQABAAACAUwAOw==";
img.src = src;
}
}
toDataURL(
'https://www.gravatar.com/avatar/d50c83cc0c6523b4d3f6085295c953e0',
function(dataUrl) {
console.log('RESULT:', dataUrl)
}
)
In detail
Supported input formats:
image/png, image/jpeg, image/jpg, image/gif, image/bmp, image/tiff, image/x-icon, image/svg+xml, image/webp, image/xxx
Supported output formats:
image/png, image/jpeg, image/webp(chrome)
Browser Support:
- http://caniuse.com/#feat=canvas
-
Internet Explorer 10 (Internet Explorer 10 just works with same origin images)
3. Approach: Images from the local file system
If you want to convert images from the users file system you need to take a different approach. Use the FileReader API:
function encodeImageFileAsURL(element) {
var file = element.files[0];
var reader = new FileReader();
reader.onloadend = function() {
console.log('RESULT', reader.result)
}
reader.readAsDataURL(file);
}
<input type="file" onchange="encodeImageFileAsURL(this)" />
You can use the HTML5 <canvas> for it:
Create a canvas, load your image into it and then use toDataURL() to get the Base64 representation (actually, it's a data: URL, but it contains the Base64-encoded image).