-
-
Save skypanther/1901680 to your computer and use it in GitHub Desktop.
Cache Remote Images
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
What if I do not want to cache the image. By default it caches then how to override it?