Skip to content

Instantly share code, notes, and snippets.

@skypanther
Forked from pec1985/app.js
Created February 24, 2012 15:46
Show Gist options
  • Star 25 You must be signed in to star a gist
  • Fork 11 You must be signed in to fork a gist
  • Save skypanther/1901680 to your computer and use it in GitHub Desktop.
Save skypanther/1901680 to your computer and use it in GitHub Desktop.
Cache Remote Images
var Utils = {
/* modified version of https://gist.github.com/1243697
* adds detection of file extension rather than hard-coding .jpg as in the original
*/
_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
});
win.add(image);
@PassHours
Copy link

What if I do not want to cache the image. By default it caches then how to override it?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment