UNPKG

14.8 kBJavaScriptView Raw
1(function (global, factory) {
2 typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) :
3 typeof define === 'function' && define.amd ? define(['exports'], factory) :
4 (factory((global.blobUtil = {})));
5}(this, (function (exports) { 'use strict';
6
7 // TODO: including these in blob-util.ts causes typedoc to generate docs for them,
8 // even with --excludePrivate ¯\_(ツ)_/¯
9 /** @private */
10 function loadImage(src, crossOrigin) {
11 return new Promise(function (resolve, reject) {
12 var img = new Image();
13 if (crossOrigin) {
14 img.crossOrigin = crossOrigin;
15 }
16 img.onload = function () {
17 resolve(img);
18 };
19 img.onerror = reject;
20 img.src = src;
21 });
22 }
23 /** @private */
24 function imgToCanvas(img) {
25 var canvas = document.createElement('canvas');
26 canvas.width = img.width;
27 canvas.height = img.height;
28 // copy the image contents to the canvas
29 var context = canvas.getContext('2d');
30 context.drawImage(img, 0, 0, img.width, img.height, 0, 0, img.width, img.height);
31 return canvas;
32 }
33
34 /* global Promise, Image, Blob, FileReader, atob, btoa,
35 BlobBuilder, MSBlobBuilder, MozBlobBuilder, WebKitBlobBuilder, webkitURL */
36 /**
37 * Shim for
38 * [`new Blob()`](https://developer.mozilla.org/en-US/docs/Web/API/Blob.Blob)
39 * to support
40 * [older browsers that use the deprecated `BlobBuilder` API](http://caniuse.com/blob).
41 *
42 * Example:
43 *
44 * ```js
45 * var myBlob = blobUtil.createBlob(['hello world'], {type: 'text/plain'});
46 * ```
47 *
48 * @param parts - content of the Blob
49 * @param properties - usually `{type: myContentType}`,
50 * you can also pass a string for the content type
51 * @returns Blob
52 */
53 function createBlob(parts, properties) {
54 parts = parts || [];
55 properties = properties || {};
56 if (typeof properties === 'string') {
57 properties = { type: properties }; // infer content type
58 }
59 try {
60 return new Blob(parts, properties);
61 }
62 catch (e) {
63 if (e.name !== 'TypeError') {
64 throw e;
65 }
66 var Builder = typeof BlobBuilder !== 'undefined'
67 ? BlobBuilder : typeof MSBlobBuilder !== 'undefined'
68 ? MSBlobBuilder : typeof MozBlobBuilder !== 'undefined'
69 ? MozBlobBuilder : WebKitBlobBuilder;
70 var builder = new Builder();
71 for (var i = 0; i < parts.length; i += 1) {
72 builder.append(parts[i]);
73 }
74 return builder.getBlob(properties.type);
75 }
76 }
77 /**
78 * Shim for
79 * [`URL.createObjectURL()`](https://developer.mozilla.org/en-US/docs/Web/API/URL.createObjectURL)
80 * to support browsers that only have the prefixed
81 * `webkitURL` (e.g. Android <4.4).
82 *
83 * Example:
84 *
85 * ```js
86 * var myUrl = blobUtil.createObjectURL(blob);
87 * ```
88 *
89 * @param blob
90 * @returns url
91 */
92 function createObjectURL(blob) {
93 return (typeof URL !== 'undefined' ? URL : webkitURL).createObjectURL(blob);
94 }
95 /**
96 * Shim for
97 * [`URL.revokeObjectURL()`](https://developer.mozilla.org/en-US/docs/Web/API/URL.revokeObjectURL)
98 * to support browsers that only have the prefixed
99 * `webkitURL` (e.g. Android <4.4).
100 *
101 * Example:
102 *
103 * ```js
104 * blobUtil.revokeObjectURL(myUrl);
105 * ```
106 *
107 * @param url
108 */
109 function revokeObjectURL(url) {
110 return (typeof URL !== 'undefined' ? URL : webkitURL).revokeObjectURL(url);
111 }
112 /**
113 * Convert a `Blob` to a binary string.
114 *
115 * Example:
116 *
117 * ```js
118 * blobUtil.blobToBinaryString(blob).then(function (binaryString) {
119 * // success
120 * }).catch(function (err) {
121 * // error
122 * });
123 * ```
124 *
125 * @param blob
126 * @returns Promise that resolves with the binary string
127 */
128 function blobToBinaryString(blob) {
129 return new Promise(function (resolve, reject) {
130 var reader = new FileReader();
131 var hasBinaryString = typeof reader.readAsBinaryString === 'function';
132 reader.onloadend = function () {
133 var result = reader.result || '';
134 if (hasBinaryString) {
135 return resolve(result);
136 }
137 resolve(arrayBufferToBinaryString(result));
138 };
139 reader.onerror = reject;
140 if (hasBinaryString) {
141 reader.readAsBinaryString(blob);
142 }
143 else {
144 reader.readAsArrayBuffer(blob);
145 }
146 });
147 }
148 /**
149 * Convert a base64-encoded string to a `Blob`.
150 *
151 * Example:
152 *
153 * ```js
154 * var blob = blobUtil.base64StringToBlob(base64String);
155 * ```
156 * @param base64 - base64-encoded string
157 * @param type - the content type (optional)
158 * @returns Blob
159 */
160 function base64StringToBlob(base64, type) {
161 var parts = [binaryStringToArrayBuffer(atob(base64))];
162 return type ? createBlob(parts, { type: type }) : createBlob(parts);
163 }
164 /**
165 * Convert a binary string to a `Blob`.
166 *
167 * Example:
168 *
169 * ```js
170 * var blob = blobUtil.binaryStringToBlob(binaryString);
171 * ```
172 *
173 * @param binary - binary string
174 * @param type - the content type (optional)
175 * @returns Blob
176 */
177 function binaryStringToBlob(binary, type) {
178 return base64StringToBlob(btoa(binary), type);
179 }
180 /**
181 * Convert a `Blob` to a binary string.
182 *
183 * Example:
184 *
185 * ```js
186 * blobUtil.blobToBase64String(blob).then(function (base64String) {
187 * // success
188 * }).catch(function (err) {
189 * // error
190 * });
191 * ```
192 *
193 * @param blob
194 * @returns Promise that resolves with the binary string
195 */
196 function blobToBase64String(blob) {
197 return blobToBinaryString(blob).then(btoa);
198 }
199 /**
200 * Convert a data URL string
201 * (e.g. `'data:image/png;base64,iVBORw0KG...'`)
202 * to a `Blob`.
203 *
204 * Example:
205 *
206 * ```js
207 * var blob = blobUtil.dataURLToBlob(dataURL);
208 * ```
209 *
210 * @param dataURL - dataURL-encoded string
211 * @returns Blob
212 */
213 function dataURLToBlob(dataURL) {
214 var type = dataURL.match(/data:([^;]+)/)[1];
215 var base64 = dataURL.replace(/^[^,]+,/, '');
216 var buff = binaryStringToArrayBuffer(atob(base64));
217 return createBlob([buff], { type: type });
218 }
219 /**
220 * Convert a `Blob` to a data URL string
221 * (e.g. `'data:image/png;base64,iVBORw0KG...'`).
222 *
223 * Example:
224 *
225 * ```js
226 * var dataURL = blobUtil.blobToDataURL(blob);
227 * ```
228 *
229 * @param blob
230 * @returns Promise that resolves with the data URL string
231 */
232 function blobToDataURL(blob) {
233 return blobToBase64String(blob).then(function (base64String) {
234 return 'data:' + blob.type + ';base64,' + base64String;
235 });
236 }
237 /**
238 * Convert an image's `src` URL to a data URL by loading the image and painting
239 * it to a `canvas`.
240 *
241 * Note: this will coerce the image to the desired content type, and it
242 * will only paint the first frame of an animated GIF.
243 *
244 * Examples:
245 *
246 * ```js
247 * blobUtil.imgSrcToDataURL('http://mysite.com/img.png').then(function (dataURL) {
248 * // success
249 * }).catch(function (err) {
250 * // error
251 * });
252 * ```
253 *
254 * ```js
255 * blobUtil.imgSrcToDataURL('http://some-other-site.com/img.jpg', 'image/jpeg',
256 * 'Anonymous', 1.0).then(function (dataURL) {
257 * // success
258 * }).catch(function (err) {
259 * // error
260 * });
261 * ```
262 *
263 * @param src - image src
264 * @param type - the content type (optional, defaults to 'image/png')
265 * @param crossOrigin - for CORS-enabled images, set this to
266 * 'Anonymous' to avoid "tainted canvas" errors
267 * @param quality - a number between 0 and 1 indicating image quality
268 * if the requested type is 'image/jpeg' or 'image/webp'
269 * @returns Promise that resolves with the data URL string
270 */
271 function imgSrcToDataURL(src, type, crossOrigin, quality) {
272 type = type || 'image/png';
273 return loadImage(src, crossOrigin).then(imgToCanvas).then(function (canvas) {
274 return canvas.toDataURL(type, quality);
275 });
276 }
277 /**
278 * Convert a `canvas` to a `Blob`.
279 *
280 * Examples:
281 *
282 * ```js
283 * blobUtil.canvasToBlob(canvas).then(function (blob) {
284 * // success
285 * }).catch(function (err) {
286 * // error
287 * });
288 * ```
289 *
290 * Most browsers support converting a canvas to both `'image/png'` and `'image/jpeg'`. You may
291 * also want to try `'image/webp'`, which will work in some browsers like Chrome (and in other browsers, will just fall back to `'image/png'`):
292 *
293 * ```js
294 * blobUtil.canvasToBlob(canvas, 'image/webp').then(function (blob) {
295 * // success
296 * }).catch(function (err) {
297 * // error
298 * });
299 * ```
300 *
301 * @param canvas - HTMLCanvasElement
302 * @param type - the content type (optional, defaults to 'image/png')
303 * @param quality - a number between 0 and 1 indicating image quality
304 * if the requested type is 'image/jpeg' or 'image/webp'
305 * @returns Promise that resolves with the `Blob`
306 */
307 function canvasToBlob(canvas, type, quality) {
308 if (typeof canvas.toBlob === 'function') {
309 return new Promise(function (resolve) {
310 canvas.toBlob(resolve, type, quality);
311 });
312 }
313 return Promise.resolve(dataURLToBlob(canvas.toDataURL(type, quality)));
314 }
315 /**
316 * Convert an image's `src` URL to a `Blob` by loading the image and painting
317 * it to a `canvas`.
318 *
319 * Note: this will coerce the image to the desired content type, and it
320 * will only paint the first frame of an animated GIF.
321 *
322 * Examples:
323 *
324 * ```js
325 * blobUtil.imgSrcToBlob('http://mysite.com/img.png').then(function (blob) {
326 * // success
327 * }).catch(function (err) {
328 * // error
329 * });
330 * ```
331 *
332 * ```js
333 * blobUtil.imgSrcToBlob('http://some-other-site.com/img.jpg', 'image/jpeg',
334 * 'Anonymous', 1.0).then(function (blob) {
335 * // success
336 * }).catch(function (err) {
337 * // error
338 * });
339 * ```
340 *
341 * @param src - image src
342 * @param type - the content type (optional, defaults to 'image/png')
343 * @param crossOrigin - for CORS-enabled images, set this to
344 * 'Anonymous' to avoid "tainted canvas" errors
345 * @param quality - a number between 0 and 1 indicating image quality
346 * if the requested type is 'image/jpeg' or 'image/webp'
347 * @returns Promise that resolves with the `Blob`
348 */
349 function imgSrcToBlob(src, type, crossOrigin, quality) {
350 type = type || 'image/png';
351 return loadImage(src, crossOrigin).then(imgToCanvas).then(function (canvas) {
352 return canvasToBlob(canvas, type, quality);
353 });
354 }
355 /**
356 * Convert an `ArrayBuffer` to a `Blob`.
357 *
358 * Example:
359 *
360 * ```js
361 * var blob = blobUtil.arrayBufferToBlob(arrayBuff, 'audio/mpeg');
362 * ```
363 *
364 * @param buffer
365 * @param type - the content type (optional)
366 * @returns Blob
367 */
368 function arrayBufferToBlob(buffer, type) {
369 return createBlob([buffer], type);
370 }
371 /**
372 * Convert a `Blob` to an `ArrayBuffer`.
373 *
374 * Example:
375 *
376 * ```js
377 * blobUtil.blobToArrayBuffer(blob).then(function (arrayBuff) {
378 * // success
379 * }).catch(function (err) {
380 * // error
381 * });
382 * ```
383 *
384 * @param blob
385 * @returns Promise that resolves with the `ArrayBuffer`
386 */
387 function blobToArrayBuffer(blob) {
388 return new Promise(function (resolve, reject) {
389 var reader = new FileReader();
390 reader.onloadend = function () {
391 var result = reader.result || new ArrayBuffer(0);
392 resolve(result);
393 };
394 reader.onerror = reject;
395 reader.readAsArrayBuffer(blob);
396 });
397 }
398 /**
399 * Convert an `ArrayBuffer` to a binary string.
400 *
401 * Example:
402 *
403 * ```js
404 * var myString = blobUtil.arrayBufferToBinaryString(arrayBuff)
405 * ```
406 *
407 * @param buffer - array buffer
408 * @returns binary string
409 */
410 function arrayBufferToBinaryString(buffer) {
411 var binary = '';
412 var bytes = new Uint8Array(buffer);
413 var length = bytes.byteLength;
414 var i = -1;
415 while (++i < length) {
416 binary += String.fromCharCode(bytes[i]);
417 }
418 return binary;
419 }
420 /**
421 * Convert a binary string to an `ArrayBuffer`.
422 *
423 * ```js
424 * var myBuffer = blobUtil.binaryStringToArrayBuffer(binaryString)
425 * ```
426 *
427 * @param binary - binary string
428 * @returns array buffer
429 */
430 function binaryStringToArrayBuffer(binary) {
431 var length = binary.length;
432 var buf = new ArrayBuffer(length);
433 var arr = new Uint8Array(buf);
434 var i = -1;
435 while (++i < length) {
436 arr[i] = binary.charCodeAt(i);
437 }
438 return buf;
439 }
440
441 exports.createBlob = createBlob;
442 exports.createObjectURL = createObjectURL;
443 exports.revokeObjectURL = revokeObjectURL;
444 exports.blobToBinaryString = blobToBinaryString;
445 exports.base64StringToBlob = base64StringToBlob;
446 exports.binaryStringToBlob = binaryStringToBlob;
447 exports.blobToBase64String = blobToBase64String;
448 exports.dataURLToBlob = dataURLToBlob;
449 exports.blobToDataURL = blobToDataURL;
450 exports.imgSrcToDataURL = imgSrcToDataURL;
451 exports.canvasToBlob = canvasToBlob;
452 exports.imgSrcToBlob = imgSrcToBlob;
453 exports.arrayBufferToBlob = arrayBufferToBlob;
454 exports.blobToArrayBuffer = blobToArrayBuffer;
455 exports.arrayBufferToBinaryString = arrayBufferToBinaryString;
456 exports.binaryStringToArrayBuffer = binaryStringToArrayBuffer;
457
458 Object.defineProperty(exports, '__esModule', { value: true });
459
460})));