danisal danisal - 15 days ago 6
Node.js Question

How to join base64 encoded images?

I have this problem, of aggregate 4 base64 encoded images as one. I'm working with node js and received a JSON with the information I need, I work that information and then I display the images in the browser like this:

'<div style="display: inline-flex;">' +
'<div>' +
'<div><img src="' + panes.content + '"></div>' +
'<div>' +
'<div><img src="' + timeAxis.content + '"></div>' +
'</div>' +
'</div>' +
'<div><img src="' + rightAxis.content + '"><img src="' + rhsStub.content + '"></div>' +

The problem with this is that the result in the browser its displayed 4 images...
I have been looking a way to joining the images, but I can't get it done, already tried with buffers and canvas, but I was not able to use canvas in the backend.
Anyone have a clue how to solve this issue?

The problem is that I have to pass 4 img tag's, and that create 4 images in the browser, like the picture bellow, that actually are 4 images that I manage to put in the correct place.
with the above code,
with the code given by rsp
I what need is a way that can create one image only, with the base64 encoded images that I received from the server, because for example if the user want to download the image, it be only one image not four.

rsp rsp

If I understand your question correctly, you just need the images touching each other with no gaps?

Maybe this would do the trick:

 '<div>' +-
  '<img src="' + panes.content + '">' +
  '<img src="' + timeAxis.content + '"><br/>' +
  '<img src="' + rightAxis.content + '">' +
  '<img src="' + rhsStub.content + '">' +

Of course you didn't show any images example so I can only guess.

Is that what you need? If not than I suggest posting an example on one of those services:

It would be much easier to answer your question if it was known what you see and what you would like to see.


You updated the question so I know that you want the image to be downloadable in one piece. You have two options here:

  1. You can decode the base64 images in Node and join the images using something like gm, imagemagick etc., then encode them again and use that in your response.
  2. You can join the images on the client side which would be easier and less work for your server. On the client side you have some images, each of which has its width and height. You can add what you need to create a new canvas with that dimensions, copy the images there using drawImage, convert the result to Base64-encoded data URL using toDataURL and create an image with src set to that data URL. The final step is to remove the original images and canvas from the DOM. If you do that then the user will have just one image ready to save.

Another way you can do it that would work differently would be like point 1 above but with saving the image on your server instead of Base64-encoding and putting its URL in the HTML. But in that case you would need to clean up the saved images after some time.