From 7831bb7b0bd94fc8054f5a1ad8dfc3f63543a37b Mon Sep 17 00:00:00 2001 From: Gerben Date: Sat, 3 Jun 2017 00:26:22 +0200 Subject: [PATCH] Add blobToDataURL. --- lib/index.js | 14 ++++++++++++++ test/test.js | 13 ++++++++++--- 2 files changed, 24 insertions(+), 3 deletions(-) diff --git a/lib/index.js b/lib/index.js index 933e323..d33f758 100644 --- a/lib/index.js +++ b/lib/index.js @@ -193,6 +193,19 @@ function dataURLToBlob(dataURL) { }); } +/** + * Convert a Blob to a data URL string + * (e.g. 'data:image/png;base64,iVBORw0KG...'). + * Returns a Promise. + * @param {Blob} blob + * @returns {Promise} Promise that resolves with the data URL string + */ +function blobToDataURL(blob) { + return blobToBase64String(blob).then(function (base64String) { + return 'data:' + blob.type + ';base64,' + base64String; + }); +} + /** * Convert an image's src URL to a data URL by loading the image and painting * it to a canvas. Returns a Promise. @@ -300,6 +313,7 @@ module.exports = { imgSrcToDataURL : imgSrcToDataURL, canvasToBlob : canvasToBlob, dataURLToBlob : dataURLToBlob, + blobToDataURL : blobToDataURL, blobToBase64String : blobToBase64String, base64StringToBlob : base64StringToBlob, binaryStringToBlob : binaryStringToBlob, diff --git a/test/test.js b/test/test.js index ffbf54b..143c349 100644 --- a/test/test.js +++ b/test/test.js @@ -103,21 +103,28 @@ describe('basic tests', function () { }); }); - it('convert to dataURL', function () { + it('convert blob to data url', function () { + var blob = blobUtil.createBlob(['foo'], 'text/plain'); + return blobUtil.blobToDataURL(blob).then(function (dataURL) { + dataURL.should.equal('data:text/plain;base64,Zm9v'); + }); + }); + + it('convert img to dataURL', function () { var img = document.getElementById('transparent'); return blobUtil.imgSrcToDataURL(img.src).then(function (url) { url.should.match(/^data:image\/png;base64/); }); }); - it('convert to dataURL 2', function () { + it('convert img to dataURL 2', function () { var img = document.getElementById('kirby'); return blobUtil.imgSrcToDataURL(img.src).then(function (url) { url.should.match(/^data:image\/png;base64/); }); }); - it('convert to dataURL 3', function () { + it('convert img to dataURL 3', function () { var img = document.getElementById('kirby'); return blobUtil.imgSrcToDataURL(img.src, 'image/jpeg').then(function (url) { url.should.match(/^data:image\/jpeg;base64/);