My favorites | Sign in
Project Home Downloads Wiki Issues Source
Checkout   Browse   Changes    
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
////////////////////////////////////////////////////////////////////////////////
//
// Copyright (c) 2009 Jacob Wright
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
////////////////////////////////////////////////////////////////////////////////
package jac.image
{
import flash.display.Bitmap;
import flash.display.BitmapData;
import flash.display.DisplayObject;
import flash.display.Loader;
import flash.display.LoaderInfo;
import flash.display.Sprite;
import flash.events.Event;
import flash.events.IOErrorEvent;
import flash.events.SecurityErrorEvent;
import flash.events.TimerEvent;
import flash.net.URLLoader;
import flash.net.URLLoaderDataFormat;
import flash.net.URLRequest;
import flash.utils.Timer;
import flash.utils.getTimer;

import flight.net.IResponse;
import flight.net.Response;
import flight.utils.Singleton;

public class ImageLibrary
{
public var provideMissingImage:Boolean = true;

[Embed(source="jac/assets/missingImage.png")]
protected var missingImageClass:Class;
protected var missingImage:BitmapData;
protected var missingImageBox:Sprite;
protected var expires:uint;
protected var timer:Timer;

/**
* Stores all the bitmap objects for images that have been loaded with
* their URL as the key.
*/
protected var images:Object = {};


public static function getInstance(scope:Object = null, defaultExpires:uint = 0):ImageLibrary
{
var lib:ImageLibrary = Singleton.getInstance(ImageLibrary, scope) as ImageLibrary;
lib.expires = defaultExpires;
return lib;
}

/**
* Constructor. Creates the default missing image bitmap data to return
* when there is an error loading an image.
*/
public function ImageLibrary()
{
var missingImageBitmap:Bitmap = new missingImageClass();
missingImage = missingImageBitmap.bitmapData;
missingImageBox = new Sprite();
missingImageBox.addChild(missingImageBitmap);
timer = new Timer(15000);
timer.addEventListener(TimerEvent.TIMER, onTimer);
}


private function onTimer():void
{
flushExpiredImages();
}


public function flushExpiredImages():void
{
var now:uint = getTimer();
for (var i:String in images) {
var data:Image = images[i];
if (data.expires && data.expires < now) {
data.bitmapData.dispose();
delete images[i];
}
}
}

public function clean():void
{
for (var i:String in images) {
var data:Image = images[i];
data.bitmapData.dispose();
delete images[i];
}
}


/**
* Will return a BitmapData object as the result of the IResponse object
* handler. If the image has been loaded once already it will call the
* result handlers immediately. Otherwise they will be called once the
* image is loaded. The image must be in a domain with a crossdomain
* policy, otherwise the bitmap data cannot be retrieved, stored,
* resized, and reused as the library needs to.
*
* @param The url for the image to be loaded.
* @param Optionally the size the image must fit to.
* @param Optionally whether the image should constrain its proportions
* when resizing to fit in the <code>size</code> parameter.
* @param Optionally set an expires time in minutes for when this image
* should be let go from memory.
*
* @return The response object which may have result or fault handlers
* added to it. This allows for async and non-async operations.
*/
public function getImage(url:String, width:uint = 0, height:uint = 0, resizeStyle:String = "constrainProportions", expires:uint = 0):IResponse
{
var response:Response = new Response();
expires = expires || this.expires;
expires = expires ? expires*60000 + getTimer() : 0;

if (url in images) {
var image:Image = images[url];
image.expires = expires;
var bitmapData:BitmapData = image.bitmapData;
response.addResultHandler(sizeImage, width, height, resizeStyle);
response.complete(bitmapData);
return response;
}

var loader:URLLoader = new URLLoader();
loader.dataFormat = URLLoaderDataFormat.BINARY;
loader.load(new URLRequest(url));
response.addCompleteEvent(loader, Event.COMPLETE);
response.addCancelEvent(loader, IOErrorEvent.IO_ERROR);
response.addCancelEvent(loader, SecurityErrorEvent.SECURITY_ERROR);
response.addResultHandler(convertToLoader)
.addResultHandler(storeImage, url, expires)
.addResultHandler(sizeImage, width, height, resizeStyle);
if (provideMissingImage) response.addFaultHandler(returnMissingImage, response, width, height);
return response;
}


/**
* Turns the results of the loader.load into bitmapdata.
*/
protected function sizeImage(data:Object, width:uint, height:uint, resizeStyle:String = "constrainProportions"):BitmapData
{
var bitmapData:BitmapData = data as BitmapData;
if (!width && !height || width == bitmapData.width && height == bitmapData.height) {
return bitmapData;
} else {
return ImageUtils.resizeImage(bitmapData, width, height, resizeStyle);
}
}


/**
* Turns the results of the loader.load into bitmapdata.
*/
protected function storeImage(data:Object, url:String, expires:uint):BitmapData
{
var content:DisplayObject = LoaderInfo(data).content;
var bitmapData:BitmapData;
if (content is Bitmap) {
bitmapData = Bitmap(content).bitmapData;
} else {
bitmapData = ImageUtils.snapshot(content);
}

images[url] = new Image(bitmapData, expires);
return bitmapData;
}


/**
*
*/
protected function convertToLoader(data:Object):Response
{
var urlLoader:URLLoader = data as URLLoader;
var response:Response = new Response();
var loader:Loader = new Loader();
response.addCompleteEvent(loader.contentLoaderInfo, Event.COMPLETE);
response.addCancelEvent(loader.contentLoaderInfo, IOErrorEvent.IO_ERROR);
response.addCancelEvent(loader.contentLoaderInfo, SecurityErrorEvent.SECURITY_ERROR);
loader.loadBytes(urlLoader.data);
return response;
}


/**
* Returns a missing image icon in place of the image when there is an
* error.
*/
protected function returnMissingImage(error:Error, response:Response, width:uint, height:uint):void
{
var image:BitmapData = missingImage;
if (width && height) {
if (missingImageBox.width != width || missingImageBox.height != height) {
missingImageBox.graphics.clear();
missingImageBox.graphics.beginFill(0, .4);
missingImageBox.graphics.drawRect(0, 0, width, height);
missingImageBox.graphics.drawRect(1, 1, width - 2, height - 2);
missingImageBox.graphics.beginFill(0, .1);
missingImageBox.graphics.drawRect(0, 0, width, height);
missingImageBox.graphics.endFill();
}
image = ImageUtils.snapshot(missingImageBox);
}
response.removeResultHandler(convertToLoader).removeResultHandler(storeImage).removeResultHandler(sizeImage).complete(image);
}
}
}

import flash.display.BitmapData;

internal final class Image
{
public var bitmapData:BitmapData;
public var expires:uint;

public function Image(bitmapData:BitmapData, expires:uint)
{
this.bitmapData = bitmapData;
this.expires = expires;
}
}

Change log

r20 by jacwright on Feb 24, 2010   Diff
Fixes and updates
Go to: 
Project members, sign in to write a code review

Older revisions

r16 by jacwright on Jan 19, 2010   Diff
Refactored out my Response classes to
use Flight Framework's. They were the
same features. I'd rather fix bugs in
just one place.
Disposing bitmapData memory for better
...
r13 by jacwright on Nov 3, 2009   Diff
Named ambiguous reponse methods to
onComplete and onFault
r7 by jacwright on Aug 24, 2009   Diff
Moving response into jac package and
modifying. Will keep API constant.
All revisions of this file

File info

Size: 8244 bytes, 245 lines
Powered by Google Project Hosting