Processing Images on the Server and Renderer Side

Writing base 64 encoded images to files

This snippet describes the way you can save an image to a file. A base 64 encoded image tipically comes from a renderer video element.

The following snippet uses Node.js 8.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
'use strict';

const util = require('util');
const fs = require('fs');
const write = util.promisify(fs.writeFile);

module.exports = ({ image, identifier, directory }) => {
try {
const extension = image.split(';')[0].match(/jpeg|png|gif/)[0];
const data = image.replace(/^data:image\/\w+;base64,/, '');
const encoding = 'base64';
const file = `${identifier}.${extension}`;
const path = path.join(directory, file);
await writeFile(path, data, encoding);
return path;
} catch (error){
console.error(error);
return null;
}
}

Parsing base 64 encoded images from array buffers to video src

If you are storing base 64 encoded images in a database you can turn them into data blobs to set them as img tag source the following way.

1
2
3
4
5
6
7
8
9

'use strict';
module.exports = (input, opts) => {
if (!input) return;
let arrayBufferView = new Uint8Array( input );
let blob = new Blob( [ arrayBufferView ], { type: opts || "image/jpg" } );
let urlCreator = window.URL || window.webkitURL;
return urlCreator.createObjectURL(blob);
};