4

I have several .png bitmaps of different dimensions, by example ./img/dog.png and ./img/cat.png. How to load the base64 string of my images via JS ? My expected data is omething like that (but far longer):

 data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAB9AAAAfQCAYAAACaOMR5AAAgAElEQ…ECBAgQIECAAAECBAgQIECAAAECBAgQIECAAAECBAicCwy83crEe3e04AAAAABJRU5ErkJggg==

Note: I wish to get back this string which is my file and just my file, not clipped, nor bigger. I will then embedded it into a SVG <image> element such:

<image href="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAB9AYAAACaOMR5AAAgAElyuiRTYUdG
EQVR4XuydB5RdZfW3nZlk0gukk4QUQiCQEEil994RFBCkigpir4j+7V2xgygiIIgggoBUQTqkQIAACQktCamk90m
yfc8492u1/PdqSlMwslaWTNz7zlv2W/d+7f3b5e8r4H/fvzjH+/3pS996akGvva+b37zm4d27Nhx5Wc+85mxNb3r
7xhtvdFi3bl1VWVnZ2ptuumldVVXVIS+88MLAo4466tlPfOIT459//vmOe+2115L61E07D1i2bFmL7373uw/V5/n
GPEOfSs8666zmq1atasa/dbvvvvva73znOwffeOONp5SXl1e89NJLX37xxRfb3HHHHatbtmy5//XXX3/yRz7ykds
+//nPP92Y+nzntddea8+PNchi/Qc/+MHKb33rW4d84xvfeMR62rdvXzl+/Ph1yKjZzjvvvMZnly5duvquu+46sHX
r1mtow7pDDjnk5aFDh64s1F/Czw3+/tvf/nakMq5Pu1555ZW29HXFF7/4xWNffvnl/s2bN6/s1q3bwj/84Q+3xhh
6EMfOmf58uVtqb/9+vXrmz399NPftey33367Ve/evVc7Hxjnqu23336l9X7qU5866Ve/+tWdH/7whz80e/bs7vvo
t9+LyLXlxz72sYfWrl274Z133qlq165dyT//+c8D7r333gN22GGHOdQ1as6cOfvy/Y4DBgy4AXncMWPGDGHsdfgW
...
...
...
vf/nakMq5Pu1555ZW29HXFF7/4xdfgvf/nakMq5Pu1sfgW29HXFF7/4xW">
</image>

My end project looks will look like that :)

enter image description here

See also: https://rugger-demast.codio.io/front/_location_map-en-wikiatlas.html , where you can download the SVG, but the png is currently just a link and will not get downloaded.

6
  • Are you really asking how to convert an image to Base64, or do you have Base64 already, it's really not clear ?= Commented May 22, 2014 at 13:48
  • I have png or jpg images, such this one. I'am newbie to base64 which I discovered today. Commented May 22, 2014 at 13:51
  • So you have an image, and you want to convert it to Base64 then ? Commented May 22, 2014 at 13:52
  • Ok, after few reading, seems I first need to get the base64. Commented May 22, 2014 at 14:05
  • Seems the question Getting BLOB data from XHR request is helpful. Commented Jul 23, 2014 at 17:21

2 Answers 2

5

OK. The solution is in this fiddle and explained as follows.

0) Objective: I wish to append something such :

<img src="data:[mime type;][charset=<charset>;][base64,][base64 data]"> // formula
<image src='data:image/png;base64,SGVsbG8s...IHdvcmxkIQ='></image>" // shortened example

1) PNG images to base 64.

PNGs are stored as BLOB, aka "a collection of binary data stored as a single entity". So I need a BLOB to Base64 converter :

var converterEngine = function (input) { // fn BLOB => Binary => Base64 ?
    var uInt8Array = new Uint8Array(input),
          i = uInt8Array.length;
    var biStr = []; //new Array(i);
    while (i--) { biStr[i] = String.fromCharCode(uInt8Array[i]);  }
    var base64 = window.btoa(biStr.join(''));
    return base64;
};

2) Loading the file and converting (data)

var getImageBase64 = function (url, callback) {
    // to comment better
    var xhr = new XMLHttpRequest(url), img64;
    xhr.open('GET', url, true); // url is the url of a PNG/JPG image.
    xhr.responseType = 'arraybuffer';
    xhr.callback = callback;
    xhr.onload  = function(){
        img64 = converterEngine(this.response); // convert BLOB to base64
        this.callback(null,img64) // callback : err, data
    };
    xhr.onerror = function(){ callback('B64 ERROR', null); };
    xhr.send();
};

// make it looks like other D3js requests
d3.uri = function(url, callback) {
    return getImageBase64(url, callback);
  };

3) Run the whole:

I run the function with the callback to append an image element with the base64 URI data.

d3.uri('http://fiddle.jshell.net/img/logo.png', function(data){ 
    $("#myImage").attr("src", "data:image/png;base64," + data);  // inject data:image in DOM
} )

Sources: I got help from Getting BLOB data from XHR request, then demoed there.

Server side

I may actually end up using server-side conversion (sources this and this). Possible ways are :

echo -n `cat file.png` | base64 > output.txt
openssl base64 < path/to/file.png | tr -d '\n' > output.txt
cat path/to/file.png | openssl base64 | tr -d '\n' > output.txt
openssl base64 -in input.png -out output.txt
Sign up to request clarification or add additional context in comments.

Comments

1

You can load text from a file into a JavaScript object with XMLHttpRequest if you want. Then you can assign the value to the xlink:href attribute for the image element with setAttribute. But the answer to this question is probably what you want.

Does SVG support embedding of bitmap images?

4 Comments

Do you mean there is a JS function to load a .png as a txt, and I will get the base64 code ?
I thought you had it as Base64. Is that something you want to do in the browser? There is a JavaScript function called btoa.
Oh... I already crossed this cat somewhere (intense memory digging)
My preference would be to convert the image before the browser gets it and load that. But if that isn't your plan, there is this Q&A that describes converting with JavaScript. It probably won't work everywhere. stackoverflow.com/questions/8022425/…

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.