UNPKG

convert-base64-to-image

Version:

This is a node package that helps you to convert base64 string created by javascript file reader to image downloadable file

36 lines (35 loc) 1.28 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.converBase64ToImage = void 0; var utils_1 = require("./utils"); /** * @name converBase64ToImage * @description Takes a base64 string that begins with data:image/jpeg;base64,/9j/4AAQSkZJRgABAQEASABIAAD// and converts it to an image. * @param {string} base64 Buffer to be converted to image. * @param {string} path Full path to write image to e.g /path/to/image.png * @requires fs * * @returns {void} */ var converBase64ToImage = function (base64, path) { try { var base64regex = /^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/; if (!base64.startsWith("data:image")) { throw new Error('Invalid base64 string'); } if (!base64) { throw new Error('Base64 can not be empty'); } if (!path) { throw new Error('Path can not be empty'); } var base64String = (0, utils_1.readBase64File)(base64); var buffer = (0, utils_1.convertBase64ToBuffer)(base64String); (0, utils_1.bufferToImageAndWriteImageToPath)(buffer, path); } catch (error) { console.log(error); process.exit(1); } }; exports.converBase64ToImage = converBase64ToImage;