UNPKG

10.9 kBMarkdownView Raw
1# JavaScript Load Image
2
3> A JavaScript library to load and transform image files.
4
5## Table of contents
6
7- [Demo](#demo)
8- [Description](#description)
9- [Setup](#setup)
10- [Usage](#usage)
11- [Image loading](#image-loading)
12- [Image scaling](#image-scaling)
13- [Requirements](#requirements)
14- [API](#api)
15- [Options](#options)
16- [Meta data parsing](#meta-data-parsing)
17- [Exif parser](#exif-parser)
18- [iOS scaling fixes](#ios-scaling-fixes)
19- [License](#license)
20- [Credits](#credits)
21
22## Demo
23[JavaScript Load Image Demo](https://blueimp.github.io/JavaScript-Load-Image/)
24
25## Description
26JavaScript Load Image is a library to load images provided as File or Blob
27objects or via URL.
28It returns an optionally scaled and/or cropped HTML img or canvas element via an
29asynchronous callback.
30It also provides a method to parse image meta data to extract Exif tags and
31thumbnails and to restore the complete image header after resizing.
32
33## Setup
34Include the (combined and minified) JavaScript Load Image script in your HTML
35markup:
36
37```html
38<script src="js/load-image.all.min.js"></script>
39```
40
41Or alternatively, choose which components you want to include:
42
43```html
44<script src="js/load-image.js"></script>
45<script src="js/load-image-ios.js"></script>
46<script src="js/load-image-orientation.js"></script>
47<script src="js/load-image-meta.js"></script>
48<script src="js/load-image-exif.js"></script>
49<script src="js/load-image-exif-map.js"></script>
50```
51
52## Usage
53
54### Image loading
55In your application code, use the **loadImage()** function like this:
56
57```js
58document.getElementById('file-input').onchange = function (e) {
59 loadImage(
60 e.target.files[0],
61 function (img) {
62 document.body.appendChild(img);
63 },
64 {maxWidth: 600} // Options
65 );
66};
67```
68
69### Image scaling
70It is also possible to use the image scaling functionality with an existing
71image:
72
73```js
74var scaledImage = loadImage.scale(
75 img, // img or canvas element
76 {maxWidth: 600}
77);
78```
79
80## Requirements
81The JavaScript Load Image library has zero dependencies.
82
83However, JavaScript Load Image is a very suitable complement to the
84[Canvas to Blob](https://github.com/blueimp/JavaScript-Canvas-to-Blob) library.
85
86## API
87The **loadImage()** function accepts a
88[File](https://developer.mozilla.org/en/DOM/File) or
89[Blob](https://developer.mozilla.org/en/DOM/Blob) object or a simple image URL
90(e.g. `'https://example.org/image.png'`) as first argument.
91
92If a [File](https://developer.mozilla.org/en/DOM/File) or
93[Blob](https://developer.mozilla.org/en/DOM/Blob) is passed as parameter, it
94returns a HTML **img** element if the browser supports the
95[URL](https://developer.mozilla.org/en/DOM/window.URL) API or a
96[FileReader](https://developer.mozilla.org/en/DOM/FileReader) object if
97supported, or **false**.
98It always returns a HTML
99[img](https://developer.mozilla.org/en/docs/HTML/Element/Img) element when
100passing an image URL:
101
102```js
103document.getElementById('file-input').onchange = function (e) {
104 var loadingImage = loadImage(
105 e.target.files[0],
106 function (img) {
107 document.body.appendChild(img);
108 },
109 {maxWidth: 600}
110 );
111 if (!loadingImage) {
112 // Alternative code ...
113 }
114};
115```
116
117The **img** element or
118[FileReader](https://developer.mozilla.org/en/DOM/FileReader) object returned by
119the **loadImage()** function allows to abort the loading process by setting the
120**onload** and **onerror** event handlers to null:
121
122```js
123document.getElementById('file-input').onchange = function (e) {
124 var loadingImage = loadImage(
125 e.target.files[0],
126 function (img) {
127 document.body.appendChild(img);
128 },
129 {maxWidth: 600}
130 );
131 loadingImage.onload = loadingImage.onerror = null;
132};
133```
134
135The second argument must be a **callback** function, which is called when the
136image has been loaded or an error occurred while loading the image. The callback
137function is passed one argument, which is either a HTML **img** element, a
138[canvas](https://developer.mozilla.org/en/HTML/Canvas) element, or an
139[Event](https://developer.mozilla.org/en/DOM/event) object of type **error**:
140
141```js
142var imageUrl = "https://example.org/image.png";
143loadImage(
144 imageUrl,
145 function (img) {
146 if(img.type === "error") {
147 console.log("Error loading image " + imageUrl);
148 } else {
149 document.body.appendChild(img);
150 }
151 },
152 {maxWidth: 600}
153);
154```
155
156## Options
157The optional third argument to **loadImage()** is a map of options:
158
159* **maxWidth**: Defines the maximum width of the img/canvas element.
160* **maxHeight**: Defines the maximum height of the img/canvas element.
161* **minWidth**: Defines the minimum width of the img/canvas element.
162* **minHeight**: Defines the minimum height of the img/canvas element.
163* **sourceWidth**: The width of the sub-rectangle of the source image to draw
164into the destination canvas.
165Defaults to the source image width and requires `canvas: true`.
166* **sourceHeight**: The height of the sub-rectangle of the source image to draw
167into the destination canvas.
168Defaults to the source image height and requires `canvas: true`.
169* **top**: The top margin of the sub-rectangle of the source image.
170Defaults to `0` and requires `canvas: true`.
171* **right**: The right margin of the sub-rectangle of the source image.
172Defaults to `0` and requires `canvas: true`.
173* **bottom**: The bottom margin of the sub-rectangle of the source image.
174Defaults to `0` and requires `canvas: true`.
175* **left**: The left margin of the sub-rectangle of the source image.
176Defaults to `0` and requires `canvas: true`.
177* **contain**: Scales the image up/down to contain it in the max dimensions if
178set to `true`.
179This emulates the CSS feature
180[background-image: contain](https://developer.mozilla.org/en-US/docs/Web/Guide/CSS/Scaling_background_images#contain).
181* **cover**: Scales the image up/down to cover the max dimensions with the image
182dimensions if set to `true`.
183This emulates the CSS feature
184[background-image: cover](https://developer.mozilla.org/en-US/docs/Web/Guide/CSS/Scaling_background_images#cover).
185* **aspectRatio**: Crops the image to the given aspect ratio (e.g. `16/9`).
186Setting the `aspectRatio` also enables the `crop` option.
187* **pixelRatio**: Defines the ratio of the canvas pixels to the physical image
188pixels on the screen.
189Should be set to `window.devicePixelRatio` unless the scaled image is not
190rendered on screen.
191Requires `canvas: true`.
192* **crop**: Crops the image to the maxWidth/maxHeight constraints if set to
193`true`.
194Enabling the `crop` option also enables the `canvas` option.
195* **orientation**: Allows to transform the canvas coordinates according to the
196EXIF orientation specification.
197Setting the `orientation` also enables the `canvas` option.
198* **canvas**: Returns the image as
199[canvas](https://developer.mozilla.org/en/HTML/Canvas) element if set to `true`.
200* **crossOrigin**: Sets the crossOrigin property on the img element for loading
201[CORS enabled images](https://developer.mozilla.org/en-US/docs/HTML/CORS_Enabled_Image).
202* **noRevoke**: By default, the
203[created object URL](https://developer.mozilla.org/en/DOM/window.URL.createObjectURL)
204is revoked after the image has been loaded, except when this option is set to
205`true`.
206
207They can be used the following way:
208
209```js
210loadImage(
211 fileOrBlobOrUrl,
212 function (img) {
213 document.body.appendChild(img);
214 },
215 {
216 maxWidth: 600,
217 maxHeight: 300,
218 minWidth: 100,
219 minHeight: 50,
220 canvas: true
221 }
222);
223```
224
225All settings are optional. By default, the image is returned as HTML **img**
226element without any image size restrictions.
227
228## Meta data parsing
229If the Load Image Meta extension is included, it is also possible to parse image
230meta data.
231The extension provides the method **loadImage.parseMetaData**, which can be used
232the following way:
233
234```js
235loadImage.parseMetaData(
236 fileOrBlob,
237 function (data) {
238 if (!data.imageHead) {
239 return;
240 }
241 // Combine data.imageHead with the image body of a resized file
242 // to create scaled images with the original image meta data, e.g.:
243 var blob = new Blob([
244 data.imageHead,
245 // Resized images always have a head size of 20 bytes,
246 // including the JPEG marker and a minimal JFIF header:
247 loadImage.blobSlice.call(resizedImage, 20)
248 ], {type: resizedImage.type});
249 },
250 {
251 maxMetaDataSize: 262144,
252 disableImageHead: false
253 }
254);
255```
256
257The third argument is an options object which defines the maximum number of
258bytes to parse for the image meta data, allows to disable the imageHead creation
259and is also passed along to segment parsers registered via loadImage extensions,
260e.g. the Exif parser.
261
262**Note:**
263Blob objects of resized images can be created via
264[canvas.toBlob()](https://github.com/blueimp/JavaScript-Canvas-to-Blob).
265
266### Exif parser
267If you include the Load Image Exif Parser extension, the **parseMetaData**
268callback **data** contains the additional property **exif** if Exif data could
269be found in the given image.
270The **exif** object stores the parsed Exif tags:
271
272```js
273var orientation = data.exif[0x0112];
274```
275
276It also provides an **exif.get()** method to retrieve the tag value via the
277tag's mapped name:
278
279```js
280var orientation = data.exif.get('Orientation');
281```
282
283By default, the only available mapped names are **Orientation** and
284**Thumbnail**.
285If you also include the Load Image Exif Map library, additional tag mappings
286become available, as well as two additional methods, **exif.getText()** and
287**exif.getAll()**:
288
289```js
290var flashText = data.exif.getText('Flash'); // e.g.: 'Flash fired, auto mode',
291
292// A map of all parsed tags with their mapped names as keys and their text values:
293var allTags = data.exif.getAll();
294```
295
296The Exif parser also adds additional options for the parseMetaData method, to
297disable certain aspects of the parser:
298
299* **disableExif**: Disables Exif parsing.
300* **disableExifThumbnail**: Disables parsing of the Exif Thumbnail.
301* **disableExifSub**: Disables parsing of the Exif Sub IFD.
302* **disableExifGps**: Disables parsing of the Exif GPS Info IFD.
303
304## iOS scaling fixes
305Scaling megapixel images in iOS (iPhone, iPad, iPod) can result in distorted
306(squashed) images.
307The Load Image iOS scaling fixes extension resolves these issues.
308
309## License
310The JavaScript Load Image script is released under the
311[MIT license](http://www.opensource.org/licenses/MIT).
312
313## Credits
314
315* Image meta data handling implementation based on the help and contribution of
316Achim Stöhr.
317* Exif tags mapping based on Jacob Seidelin's
318[exif-js](https://github.com/jseidelin/exif-js).
319* iOS image scaling fixes based on Shinichi Tomita's
320[ios-imagefile-megapixel](https://github.com/stomita/ios-imagefile-megapixel).