Converting images to a Base64 data URL


#1

Can this be made using javascript?

image to base64 data uri string converter?

You would put the image url in,
https://i.imgur.com/IqyHzfa.png

then the converter would give you this back:

<img src="data:image/png;base64,R0lGODlhEAAQAMQAAORHHOVSKudfOulrSOp3WOyDZu6QdvCchPGolfO0o/XBs/fNwfjZ0frl3/zy7////wAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACH5BAkAABAALAAAAAAQABAAAAVVICSOZGlCQAosJ6mu7fiyZeKqNKToQGDsM8hBADgUXoGAiqhSvp5QAnQKGIgUhwFUYLCVDFCrKUE1lBavAViFIDlTImbKC5Gm2hB0SlBCBMQiB0UjIQA7" />

Is this something that can be made?

It would work similar to this:

But instead of SVG to base64,

It would be:
image/png to base64 instead.

<title>SVG code to base64 conversion</title>

<link rel="stylesheet" href="screen.css" media="screen">

<style media="screen">
body {
    background-color: #f0f0f0;
    font: 1em/150% verdana, arial, helvetica, sans-serif;
 }

svg{
    display:none;
 }

h1 {
   font-size: 1.5em;
   text-align: center;
 }

#base{
    max-width: 50em;
    padding: 1em;
    margin:auto;
    border: 0.062em solid #000;
    background-color: #fff;
    word-break: break-all;
 }
</style>

</head>
<body> 

  <h1>SVG code to base64 conversion</h1>

  <div id="base"></div>

 <svg viewBox="0 0 1226 1481">
  <path d="M0 1394V87C0 46.3 13.3 19.8 40 7.5 66.7-4.8 98.7.3 136 23l1034 634c37.3 22.7 56 50.3 56 83s-18.7 60.3-56 83L136 1458c-37.3 22.7-69.3 27.8-96 15.5-26.7-12.3-40-38.8-40-79.5z" fill="red"/>
 </svg>

<script>
(function(w,d) {
   'use strict';
   var svg = new XMLSerializer().serializeToString(d.getElementsByTagName( 'svg' )[ 0 ] );
   var base64 = w.btoa( svg );
   d.getElementById( 'base' ).appendChild( d.createTextNode( 'data:image/svg+xml;base64,' + base64 ) );
}(window, document));
</script>

Converting an SVG Path to a Base64 data uri string
#2

You can do this by first drawing the image to a canvas, which provides a method to directly get the image as data URL:

var getDataUrl = function (img) {
  var canvas = document.createElement('canvas')
  var ctx = canvas.getContext('2d')

  canvas.width = img.width
  canvas.height = img.height
  ctx.drawImage(img, 0, 0)

  // If the image is not png, the format
  // must be specified here
  return canvas.toDataURL()
}

// You can then get the data URL when the image got loaded:
var img = document.querySelector('img')

img.addEventListener('load', function (event) {
  var dataUrl = getDataUrl(event.currentTarget)
  console.log(dataUrl)
})

Note that the image has to be on the same domain though, otherwise it may not work due to CORS.


#3

I'm confused on how to make a jsfiddle of it:
https://jsfiddle.net/ymtnszsn/4/


#4

Hi there asasass,

Here is @m3g4p0p's javascript code added to an HTML document...

<!DOCTYPE HTML>
<html lang="en">
<head>

<meta charset="utf-8">
<meta name="viewport" content="width=device-width,height=device-height,initial-scale=1">

<title>Image to base64 conversion</title>

<style media="screen">
body {
    background-color: #f0f0f0;
    font: 1em/150% verdana, arial, helvetica, sans-serif;
 }
h1 {
   font-size: 1.5em;
   text-align: center;
 }

img {
    display:none;
 }

#base64 {
    max-width: 50em;
    padding: 1em;
    margin:auto;
    border: 0.062em solid #000;
    background-color: #fff;
    word-break: break-all;
 }
</style>

</head>
<body> 

<h1>Image to base64 conversion</h1>

<!-- 
    ******************************************************

    Note - you cannot use https://i.imgur.com/IqyHzfa.png  
    The image must be on the same domain.

    ******************************************************
 -->
<img src="IqyHzfa.png" alt=""> 

<div id="base64"></div>
<script>
 ( function( d ) {
   'use strict';

   var getDataUrl = function (img) {
   var canvas = document.createElement('canvas');
       canvas.width = img.width;
       canvas.height = img.height;
   var ctx = canvas.getContext('2d');
       ctx.drawImage( img, 0, 0 ); 
       return canvas.toDataURL( );
   };

   var img = d.querySelector( 'img' );
       img.addEventListener( 'load', 
          function ( event ) {
             var dataUrl = getDataUrl( event.currentTarget);
             //console.log( dataUrl );
             d.querySelector( '#base64' ).appendChild(  d.createTextNode( dataUrl ) );
           });
 }( document ));
</script>

</body>
</html>

coothead


#5

Thank you....


#6

Can this be made to do:

mp3 to base64 data uri?

I was reading this.
http://www.iandevlin.com/blog/2012/09/html5/html5-media-and-data-uri/

2nd thoughts, I don't think this would be a good idea cause the data uri would be way too long.

And why someone would do that, I have no idea.


#7
Note - you cannot use https://i.imgur.com/IqyHzfa.png  
The image must be on the same domain.

Why not?

Is there a way I can use that?


#8

How would I do something like this using javascript where I can browse for the image, and then it turns it into a data uri string?

What would the code be to do that?

http://tools.dynamicdrive.com/imagetobase64/

https://www.browserling.com/tools/image-to-base64

Something like this:

Where you would browse for the image, then it would give you the data uri


#9

Something like this with a browse button

https://jsfiddle.net/ymtnszsn/16/


#10

I'm not so sure JavaScript is the appropriate tool for the job. IMHO, it would be better to write a desktop utility in Java. Or another language, and maybe on a server. Just not JavaScript.


#11

How would I keep the top part, keep the image,

but remove the href?
http://jsfiddle.net/xztfbx1m/271/


#12

URI lengths of longer than 2000 characters do cause problems in web browsers, so I don't think that it's appropriate to stuff base64 image code in the URI, especially if that results in a URI that's longer than 2000 characters.

For example, Internet Explorer has a maximum URI length of 2083 characters.
https://support.microsoft.com/en-nz/help/208427/maximum-url-length-is-2-083-characters-in-internet-explorer


#13

You're right, it tends to be good for tiny images, as opposed to larger ones.

If you put an image inside the javascript, is the http still called when the page loads?


#14

Which http are you talking about?


#15

The biggest reason: it saves HTTP Requests. Other than pure document size, this is the #1 factor concerning how fast a page loads. Less = better.


#16

The browser having to download the base64 image code in with the JavaScript code, will delay the loading of the page because no scripting can occur until after the script as fully completed downloading.


#17

If you want a solution to rapidly load images, load them in parallel using Ajax requests instead.


#18

Can someone separate the javascript into the javascript part, and the html into the html part.
https://jsfiddle.net/8zdt7no0/1/

First add an image to see if it works.

Then separate it out.

Then, add an image again, and see if it still works.


#19

It crashed my tab when trying the first time. Is there a filesize limit? I chose to do it on a 4 megabyte picture


#20

Try a smaller size.

Trying to separate it on here:
https://jsfiddle.net/8zdt7no0/1/

online version:
https://thiscouldbebetter.neocities.org/filetodataurl.html