index.js 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. 'use strict';
  2. /**
  3. * Module dependencies.
  4. * @private
  5. */
  6. var fs = require('fs');
  7. /**
  8. * Module exports.
  9. * @public
  10. */
  11. module.exports = base64ToImage;
  12. /**
  13. * Change base64Str to image and write image file with
  14. the specified file name to the specified file path.
  15. * @param {String} base64 string (mandatory)
  16. * @param {String} file path e.g. /opt/temp/uploads/ (mandatory)
  17. * @return {Object} optionsObj holds image type, image filename, debug e.g.{'fileName':fileName, 'type':type,'debug':true} (optional)
  18. * @public
  19. */
  20. function base64ToImage(base64Str, path, optionalObj) {
  21. if (!base64Str || !path) {
  22. throw new Error('Missing mandatory arguments base64 string and/or path string');
  23. }
  24. var optionalObj = optionalObj || {};
  25. var imageBuffer = decodeBase64Image(base64Str);
  26. var imageType = optionalObj.type || imageBuffer.type || 'png';
  27. var fileName = optionalObj.fileName || 'img-' + Date.now();
  28. var abs;
  29. var fileName = '' + fileName;
  30. if (fileName.indexOf('.') === -1) {
  31. imageType = imageType.replace('image/', '');
  32. fileName = fileName + '.' + imageType;
  33. }
  34. abs = path + fileName;
  35. fs.writeFile(abs, imageBuffer.data, 'base64', function(err) {
  36. if (err && optionalObj.debug) {
  37. console.log("File image write error", err);
  38. }
  39. });
  40. return {
  41. 'imageType': imageType,
  42. 'fileName': fileName
  43. };
  44. };
  45. /**
  46. * Decode base64 string to buffer.
  47. *
  48. * @param {String} base64Str string
  49. * @return {Object} Image object with image type and data buffer.
  50. * @public
  51. */
  52. function decodeBase64Image(base64Str) {
  53. var matches = base64Str.match(/^data:([A-Za-z-+\/]+);base64,(.+)$/);
  54. var image = {};
  55. if (!matches || matches.length !== 3) {
  56. throw new Error('Invalid base64 string');
  57. }
  58. image.type = matches[1];
  59. image.data = new Buffer(matches[2], 'base64');
  60. return image;
  61. }