1 // Copyright 2014 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 // This function takes an object |imageSpec| with the key |path| -
6 // corresponding to the internet URL to be translated - and optionally
7 // |width| and |height| which are the maximum dimensions to be used when
8 // converting the image.
9 function loadImageData(imageSpec
, callbacks
) {
10 var path
= imageSpec
.path
;
11 var img
= new Image();
12 if (typeof callbacks
.onerror
=== 'function') {
13 img
.onerror = function() {
14 callbacks
.onerror({ problem
: 'could_not_load', path
: path
});
17 img
.onload = function() {
18 var canvas
= document
.createElement('canvas');
20 if (img
.width
<= 0 || img
.height
<= 0) {
21 callbacks
.onerror({ problem
: 'image_size_invalid', path
: path
});
26 if (imageSpec
.width
&& imageSpec
.width
< img
.width
)
27 scaleFactor
= imageSpec
.width
/ img
.width
;
29 if (imageSpec
.height
&& imageSpec
.height
< img
.height
) {
30 var heightScale
= imageSpec
.height
/ img
.height
;
31 if (heightScale
< scaleFactor
)
32 scaleFactor
= heightScale
;
35 canvas
.width
= img
.width
* scaleFactor
;
36 canvas
.height
= img
.height
* scaleFactor
;
38 var canvas_context
= canvas
.getContext('2d');
39 canvas_context
.clearRect(0, 0, canvas
.width
, canvas
.height
);
40 canvas_context
.drawImage(img
, 0, 0, canvas
.width
, canvas
.height
);
42 var imageData
= canvas_context
.getImageData(
43 0, 0, canvas
.width
, canvas
.height
);
44 if (typeof callbacks
.oncomplete
=== 'function') {
46 imageData
.width
, imageData
.height
, imageData
.data
.buffer
);
49 if (typeof callbacks
.onerror
=== 'function') {
50 callbacks
.onerror({ problem
: 'data_url_unavailable', path
: path
});
57 function on_complete_index(index
, err
, loading
, finished
, callbacks
) {
58 return function(width
, height
, imageData
) {
59 delete loading
[index
];
60 finished
[index
] = { width
: width
, height
: height
, data
: imageData
};
62 callbacks
.onerror(index
);
63 if ($Object
.keys(loading
).length
== 0)
64 callbacks
.oncomplete(finished
);
68 function loadAllImages(imageSpecs
, callbacks
) {
69 var loading
= {}, finished
= [],
72 for (var index
= 0; index
< imageSpecs
.length
; index
++) {
73 loading
[index
] = imageSpecs
[index
];
74 loadImageData(imageSpecs
[index
], {
75 oncomplete
: on_complete_index(index
, false, loading
, finished
, callbacks
),
76 onerror
: on_complete_index(index
, true, loading
, finished
, callbacks
)
81 exports
.loadImageData
= loadImageData
;
82 exports
.loadAllImages
= loadAllImages
;