UNPKG

14.6 kBMarkdownView Raw
1blob-util [![Build Status](https://travis-ci.org/nolanlawson/blob-util.svg)](https://travis-ci.org/nolanlawson/blob-util) [![TypeScript](https://img.shields.io/badge/%3C%2F%3E-typescript-blue.svg)](http://www.typescriptlang.org/)
2=====
3
4`blob-util` is a [Blob](https://developer.mozilla.org/en-US/docs/Web/API/Blob?redirectlocale=en-US&redirectslug=DOM%2FBlob) library for busy people.
5
6It offers a small set of cross-browser utilities for translating Blobs to and from different formats:
7
8* `<img/>` tags
9* base 64 strings
10* binary strings
11* ArrayBuffers
12* data URLs
13* canvas
14
15It's also a good pairing with the attachment API in [PouchDB](http://pouchdb.com).
16
17**Note**: this is a browser library. For Node.js, see [Buffers](http://nodejs.org/api/buffer.html).
18
19**Topics**:
20
21* [Install](#usage)
22* [Browser support](#browser-support)
23* [Tutorial](#tutorial)
24* [Playground](http://nolanlawson.github.io/blob-util)
25* [API](#api)
26
27Install
28------
29
30Via npm:
31
32```bash
33npm install blob-util
34```
35
36ES modules are supported:
37
38```js
39import { canvasToBlob } from 'blob-util'
40canvasToBlob(canvas, 'image/png').then(/* ... */)
41```
42
43Or as a script tag:
44
45```html
46<script src="https://unpkg.com/blob-util/dist/blob-util.min.js"></script>
47```
48
49Then it's available as a global `blobUtil` object:
50
51```js
52blobUtil.canvasToBlob(canvas, 'image/png').then(/* ... */)
53```
54
55Browser support
56-----
57
58As of v2.0.0, a built-in `Promise` polyfill is no longer provided. Assuming you provide a `Promise`
59polyfill, the supported browsers are:
60
61* Firefox
62* Chrome
63* Edge
64* IE 10+
65* Safari 6+
66* iOS 6+
67* Android 4+
68* Any browser with either `Blob` or the older `BlobBuilder`; see [caniuse](http://caniuse.com/#search=blob) for details.
69
70Tutorial
71--------
72
73Blobs (<strong>b</strong>inary <strong>l</strong>arge <strong>ob</strong>jects) are the modern way of working with binary data in the browser. The browser support is [very good](http://caniuse.com/#search=blob).
74
75Once you have a Blob, you can make it available offline by storing it in [IndexedDB](http://www.w3.org/TR/IndexedDB/), [PouchDB](http://pouchdb.com/), [LocalForage](https://mozilla.github.io/localForage/), or other in-browser databases. So it's the perfect format for working with offline images, sound, and video.
76
77A [File](https://developer.mozilla.org/en-US/docs/Web/API/File) is also a Blob. So if you have an `<input type="file">` in your page, you can let your users upload any file and then work with it as a Blob.
78
79### Example
80
81Here's Kirby. He's a famous little Blob.
82
83<img id="kirby" alt="Kirby" src="./test/kirby.gif"/>
84
85So let's fulfill his destiny, and convert him to a real `Blob` object.
86
87```js
88var img = document.getElementById('kirby');
89
90blobUtil.imgSrcToBlob(img.src).then(function (blob) {
91 // ladies and gents, we have a blob
92}).catch(function (err) {
93 // image failed to load
94});
95```
96
97(Don't worry, this won't download the image twice, because browsers are smart.)
98
99Now that we have a `Blob`, we can convert it to a URL and use that as the source for another `<img/>` tag:
100
101```js
102var blobURL = blobUtil.createObjectURL(blob);
103
104var newImg = document.createElement('img');
105newImg.src = blobURL;
106
107document.body.appendChild(newImg);
108```
109
110So now we have two Kirbys - one with a normal URL, and the other with a blob URL. You can try this out yourself in the [blob-util playground](http://nolanlawson.github.io/blob-util). Super fun!
111
112<img src="blob-util.gif"/>
113
114
115API
116-------
117
118<!-- begin insert API -->
119
120## Index
121
122### Functions
123
124* [arrayBufferToBinaryString](#arraybuffertobinarystring)
125* [arrayBufferToBlob](#arraybuffertoblob)
126* [base64StringToBlob](#base64stringtoblob)
127* [binaryStringToArrayBuffer](#binarystringtoarraybuffer)
128* [binaryStringToBlob](#binarystringtoblob)
129* [blobToArrayBuffer](#blobtoarraybuffer)
130* [blobToBase64String](#blobtobase64string)
131* [blobToBinaryString](#blobtobinarystring)
132* [blobToDataURL](#blobtodataurl)
133* [canvasToBlob](#canvastoblob)
134* [createBlob](#createblob)
135* [createObjectURL](#createobjecturl)
136* [dataURLToBlob](#dataurltoblob)
137* [imgSrcToBlob](#imgsrctoblob)
138* [imgSrcToDataURL](#imgsrctodataurl)
139* [revokeObjectURL](#revokeobjecturl)
140
141---
142
143## Functions
144
145<a id="arraybuffertobinarystring"></a>
146
147### arrayBufferToBinaryString
148
149**arrayBufferToBinaryString**(buffer: *`ArrayBuffer`*): `string`
150
151Convert an `ArrayBuffer` to a binary string.
152
153Example:
154
155```js
156var myString = blobUtil.arrayBufferToBinaryString(arrayBuff)
157```
158
159**Parameters:**
160
161| Param | Type | Description |
162| ------ | ------ | ------ |
163| buffer | `ArrayBuffer` | array buffer |
164
165**Returns:** `string`
166binary string
167
168___
169<a id="arraybuffertoblob"></a>
170
171### arrayBufferToBlob
172
173**arrayBufferToBlob**(buffer: *`ArrayBuffer`*, type?: *`string`*): `Blob`
174
175Convert an `ArrayBuffer` to a `Blob`.
176
177Example:
178
179```js
180var blob = blobUtil.arrayBufferToBlob(arrayBuff, 'audio/mpeg');
181```
182
183**Parameters:**
184
185| Param | Type | Description |
186| ------ | ------ | ------ |
187| buffer | `ArrayBuffer` | - |
188| `Optional` type | `string` | the content type (optional) |
189
190**Returns:** `Blob`
191Blob
192
193___
194<a id="base64stringtoblob"></a>
195
196### base64StringToBlob
197
198**base64StringToBlob**(base64: *`string`*, type?: *`string`*): `Blob`
199
200Convert a base64-encoded string to a `Blob`.
201
202Example:
203
204```js
205var blob = blobUtil.base64StringToBlob(base64String);
206```
207
208**Parameters:**
209
210| Param | Type | Description |
211| ------ | ------ | ------ |
212| base64 | `string` | base64-encoded string |
213| `Optional` type | `string` | the content type (optional) |
214
215**Returns:** `Blob`
216Blob
217
218___
219<a id="binarystringtoarraybuffer"></a>
220
221### binaryStringToArrayBuffer
222
223**binaryStringToArrayBuffer**(binary: *`string`*): `ArrayBuffer`
224
225Convert a binary string to an `ArrayBuffer`.
226
227```js
228var myBuffer = blobUtil.binaryStringToArrayBuffer(binaryString)
229```
230
231**Parameters:**
232
233| Param | Type | Description |
234| ------ | ------ | ------ |
235| binary | `string` | binary string |
236
237**Returns:** `ArrayBuffer`
238array buffer
239
240___
241<a id="binarystringtoblob"></a>
242
243### binaryStringToBlob
244
245**binaryStringToBlob**(binary: *`string`*, type?: *`string`*): `Blob`
246
247Convert a binary string to a `Blob`.
248
249Example:
250
251```js
252var blob = blobUtil.binaryStringToBlob(binaryString);
253```
254
255**Parameters:**
256
257| Param | Type | Description |
258| ------ | ------ | ------ |
259| binary | `string` | binary string |
260| `Optional` type | `string` | the content type (optional) |
261
262**Returns:** `Blob`
263Blob
264
265___
266<a id="blobtoarraybuffer"></a>
267
268### blobToArrayBuffer
269
270**blobToArrayBuffer**(blob: *`Blob`*): `Promise`<`ArrayBuffer`>
271
272Convert a `Blob` to an `ArrayBuffer`.
273
274Example:
275
276```js
277blobUtil.blobToArrayBuffer(blob).then(function (arrayBuff) {
278 // success
279}).catch(function (err) {
280 // error
281});
282```
283
284**Parameters:**
285
286| Param | Type | Description |
287| ------ | ------ | ------ |
288| blob | `Blob` | - |
289
290**Returns:** `Promise`<`ArrayBuffer`>
291Promise that resolves with the `ArrayBuffer`
292
293___
294<a id="blobtobase64string"></a>
295
296### blobToBase64String
297
298**blobToBase64String**(blob: *`Blob`*): `Promise`<`string`>
299
300Convert a `Blob` to a binary string.
301
302Example:
303
304```js
305blobUtil.blobToBase64String(blob).then(function (base64String) {
306 // success
307}).catch(function (err) {
308 // error
309});
310```
311
312**Parameters:**
313
314| Param | Type | Description |
315| ------ | ------ | ------ |
316| blob | `Blob` | - |
317
318**Returns:** `Promise`<`string`>
319Promise that resolves with the binary string
320
321___
322<a id="blobtobinarystring"></a>
323
324### blobToBinaryString
325
326**blobToBinaryString**(blob: *`Blob`*): `Promise`<`string`>
327
328Convert a `Blob` to a binary string.
329
330Example:
331
332```js
333blobUtil.blobToBinaryString(blob).then(function (binaryString) {
334 // success
335}).catch(function (err) {
336 // error
337});
338```
339
340**Parameters:**
341
342| Param | Type | Description |
343| ------ | ------ | ------ |
344| blob | `Blob` | - |
345
346**Returns:** `Promise`<`string`>
347Promise that resolves with the binary string
348
349___
350<a id="blobtodataurl"></a>
351
352### blobToDataURL
353
354**blobToDataURL**(blob: *`Blob`*): `Promise`<`string`>
355
356Convert a `Blob` to a data URL string (e.g. `'data:image/png;base64,iVBORw0KG...'`).
357
358Example:
359
360```js
361var dataURL = blobUtil.blobToDataURL(blob);
362```
363
364**Parameters:**
365
366| Param | Type | Description |
367| ------ | ------ | ------ |
368| blob | `Blob` | - |
369
370**Returns:** `Promise`<`string`>
371Promise that resolves with the data URL string
372
373___
374<a id="canvastoblob"></a>
375
376### canvasToBlob
377
378**canvasToBlob**(canvas: *`HTMLCanvasElement`*, type?: *`string`*, quality?: *`number`*): `Promise`<`Blob`>
379
380Convert a `canvas` to a `Blob`.
381
382Examples:
383
384```js
385blobUtil.canvasToBlob(canvas).then(function (blob) {
386 // success
387}).catch(function (err) {
388 // error
389});
390```
391
392Most browsers support converting a canvas to both `'image/png'` and `'image/jpeg'`. You may 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'`):
393
394```js
395blobUtil.canvasToBlob(canvas, 'image/webp').then(function (blob) {
396 // success
397}).catch(function (err) {
398 // error
399});
400```
401
402**Parameters:**
403
404| Param | Type | Description |
405| ------ | ------ | ------ |
406| canvas | `HTMLCanvasElement` | HTMLCanvasElement |
407| `Optional` type | `string` | the content type (optional, defaults to 'image/png') |
408| `Optional` quality | `number` | a number between 0 and 1 indicating image quality if the requested type is 'image/jpeg' or 'image/webp' |
409
410**Returns:** `Promise`<`Blob`>
411Promise that resolves with the `Blob`
412
413___
414<a id="createblob"></a>
415
416### createBlob
417
418**createBlob**(parts: *`Array`<`any`>*, properties?: * `BlobPropertyBag` &#124; `string`*): `Blob`
419
420Shim for [`new Blob()`](https://developer.mozilla.org/en-US/docs/Web/API/Blob.Blob) to support [older browsers that use the deprecated `BlobBuilder` API](http://caniuse.com/blob).
421
422Example:
423
424```js
425var myBlob = blobUtil.createBlob(['hello world'], {type: 'text/plain'});
426```
427
428**Parameters:**
429
430| Param | Type | Description |
431| ------ | ------ | ------ |
432| parts | `Array`<`any`> | content of the Blob |
433| `Optional` properties | `BlobPropertyBag` &#124; `string`| usually `{type: myContentType}`, you can also pass a string for the content type |
434
435**Returns:** `Blob`
436Blob
437
438___
439<a id="createobjecturl"></a>
440
441### createObjectURL
442
443**createObjectURL**(blob: *`Blob`*): `string`
444
445Shim for [`URL.createObjectURL()`](https://developer.mozilla.org/en-US/docs/Web/API/URL.createObjectURL) to support browsers that only have the prefixed `webkitURL` (e.g. Android <4.4).
446
447Example:
448
449```js
450var myUrl = blobUtil.createObjectURL(blob);
451```
452
453**Parameters:**
454
455| Param | Type | Description |
456| ------ | ------ | ------ |
457| blob | `Blob` | - |
458
459**Returns:** `string`
460url
461
462___
463<a id="dataurltoblob"></a>
464
465### dataURLToBlob
466
467**dataURLToBlob**(dataURL: *`string`*): `Blob`
468
469Convert a data URL string (e.g. `'data:image/png;base64,iVBORw0KG...'`) to a `Blob`.
470
471Example:
472
473```js
474var blob = blobUtil.dataURLToBlob(dataURL);
475```
476
477**Parameters:**
478
479| Param | Type | Description |
480| ------ | ------ | ------ |
481| dataURL | `string` | dataURL-encoded string |
482
483**Returns:** `Blob`
484Blob
485
486___
487<a id="imgsrctoblob"></a>
488
489### imgSrcToBlob
490
491**imgSrcToBlob**(src: *`string`*, type?: *`string`*, crossOrigin?: *`string`*, quality?: *`number`*): `Promise`<`Blob`>
492
493Convert an image's `src` URL to a `Blob` by loading the image and painting it to a `canvas`.
494
495Note: this will coerce the image to the desired content type, and it will only paint the first frame of an animated GIF.
496
497Examples:
498
499```js
500blobUtil.imgSrcToBlob('http://mysite.com/img.png').then(function (blob) {
501 // success
502}).catch(function (err) {
503 // error
504});
505```
506```js
507blobUtil.imgSrcToBlob('http://some-other-site.com/img.jpg', 'image/jpeg',
508 'Anonymous', 1.0).then(function (blob) {
509 // success
510}).catch(function (err) {
511 // error
512});
513```
514
515**Parameters:**
516
517| Param | Type | Description |
518| ------ | ------ | ------ |
519| src | `string` | image src |
520| `Optional` type | `string` | the content type (optional, defaults to 'image/png') |
521| `Optional` crossOrigin | `string` | for CORS-enabled images, set this to 'Anonymous' to avoid "tainted canvas" errors |
522| `Optional` quality | `number` | a number between 0 and 1 indicating image quality if the requested type is 'image/jpeg' or 'image/webp' |
523
524**Returns:** `Promise`<`Blob`>
525Promise that resolves with the `Blob`
526
527___
528<a id="imgsrctodataurl"></a>
529
530### imgSrcToDataURL
531
532**imgSrcToDataURL**(src: *`string`*, type?: *`string`*, crossOrigin?: *`string`*, quality?: *`number`*): `Promise`<`string`>
533
534Convert an image's `src` URL to a data URL by loading the image and painting it to a `canvas`.
535
536Note: this will coerce the image to the desired content type, and it will only paint the first frame of an animated GIF.
537
538Examples:
539
540```js
541blobUtil.imgSrcToDataURL('http://mysite.com/img.png').then(function (dataURL) {
542 // success
543}).catch(function (err) {
544 // error
545});
546```
547```js
548blobUtil.imgSrcToDataURL('http://some-other-site.com/img.jpg', 'image/jpeg',
549 'Anonymous', 1.0).then(function (dataURL) {
550 // success
551}).catch(function (err) {
552 // error
553});
554```
555
556**Parameters:**
557
558| Param | Type | Description |
559| ------ | ------ | ------ |
560| src | `string` | image src |
561| `Optional` type | `string` | the content type (optional, defaults to 'image/png') |
562| `Optional` crossOrigin | `string` | for CORS-enabled images, set this to 'Anonymous' to avoid "tainted canvas" errors |
563| `Optional` quality | `number` | a number between 0 and 1 indicating image quality if the requested type is 'image/jpeg' or 'image/webp' |
564
565**Returns:** `Promise`<`string`>
566Promise that resolves with the data URL string
567
568___
569<a id="revokeobjecturl"></a>
570
571### revokeObjectURL
572
573**revokeObjectURL**(url: *`string`*): `void`
574
575Shim for [`URL.revokeObjectURL()`](https://developer.mozilla.org/en-US/docs/Web/API/URL.revokeObjectURL) to support browsers that only have the prefixed `webkitURL` (e.g. Android <4.4).
576
577Example:
578
579```js
580blobUtil.revokeObjectURL(myUrl);
581```
582
583**Parameters:**
584
585| Param | Type | Description |
586| ------ | ------ | ------ |
587| url | `string` | |
588
589**Returns:** `void`
590
591___
592
593
594
595<!-- end insert API -->
596
597Credits
598----
599
600Thanks to the rest of [the PouchDB team](https://github.com/pouchdb/pouchdb/graphs/contributors) for figuring most of this crazy stuff out.
601
602Building the library
603----
604
605 npm install
606 npm run build
607
608Testing the library
609----
610
611 npm install
612
613Then to test in the browser using Saucelabs:
614
615 npm test
616
617Or to test locally in your browser of choice:
618
619 npm run test-local
620
621To build the API docs and insert them in the README:
622
623 npm run doc
\No newline at end of file