Skip to content

Instantly share code, notes, and snippets.

@serebro
Created April 24, 2014 21:34
Show Gist options
  • Save serebro/11270342 to your computer and use it in GitHub Desktop.
Save serebro/11270342 to your computer and use it in GitHub Desktop.
/*
Caching remote images
As you know, you can display local and remote images in a Titanium ImageView.
When loading remote images, you should set the defaultImage property to local image,
which will be displayed while the remote image is being downloaded.
Furthermore, you should cache remote images that will be frequently accessed for two reasons:
first so that subsequent uses of your app will load those images more quickly,
and second, so that the images aren't re-downloaded consuming users' data quotas unnecessarily.
Below is a sample utility function that you can use to cache a remote image
to the app's ApplicationDataDirectory.
(In addition to below, you'll find this code at https://gist.github.com/1901680).
*/
var Utils = {
/* modified version of https://gist.github.com/1243697 */
_getExtension: function(fn) {
// from http://stackoverflow.com/a/680982/292947
var re = /(?:\.([^.]+))?$/;
var tmpext = re.exec(fn)[1];
return (tmpext) ? tmpext : '';
},
RemoteImage: function(a){
a = a || {};
var md5;
var needsToSave = false;
var savedFile;
if(a.image){
md5 = Ti.Utils.md5HexDigest(a.image)+this._getExtension(a.image);
savedFile = Titanium.Filesystem.getFile(Titanium.Filesystem.applicationDataDirectory,md5);
if(savedFile.exists()){
a.image = savedFile;
} else {
needsToSave = true;
}
}
var image = Ti.UI.createImageView(a);
if(needsToSave === true){
function saveImage(e){
image.removeEventListener('load',saveImage);
savedFile.write(
Ti.UI.createImageView({image:image.image,width:'auto',height:'auto'}).toImage()
);
}
image.addEventListener('load',saveImage);
}
return image;
}
};
// example usage
var image = Utils.RemoteImage({
image:'http://farm7.staticflickr.com/6059/6262552465_e53bccbd52_z.jpg',
defaultImage:'KS_nav_ui.png',
width:300,
height:200,
top:20
});
win2.add(image);
/*
Summary
Optimizing images will help you create smaller installation (IPA/APK) files.
The same is true of using defaultImage placeholders and downloading/caching final images
from a remote source. You'll also minimize your user's consumption of
data bandwidth by cropping and optimizing images.
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment