问题
I am building on the Phonegap. Pretty nifty, in that I found how to build a contact list. I've finished the tutorial, and now want to add to it to better learn Phonegap.
What I would like to do is display the contact's primary photo on the item detail page. The contact photo is returning a url of "/var/ folders/45/xfgjqr4j59144x8gzq4gdrpw0000gn/T/photo_004.jpg". My question is how can I actually display that? I'm assuming the / var directory is not accessible via the img tag (as the image is not displaying), but I assume that file is accessible through a Phonegap API. I further assume that it is somehow through the File API. That's where my train of thought details and I can go no further.
Can anyone help me get back on track? Anyone have an example of how to display the image from the contact list?
回答1:
Check this link on PhoneGap API File documentation. You could read the file as base64 string, and embed it in the HTML img tag:
<img alt="Embedded Image" src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADIA..." />
Maybe like this, using PhoneGap 2.5, for example:
function loadImage(imgId, fileName){
window.requestFileSystem(LocalFileSystem.PERSISTENT, 0,
function(fileSystem){
fileSystem.root.getFile(fileName, null,
function(fileEntry) {
fileEntry.file(
function(file){
var reader = new FileReader();
reader.onloadend = function(evt) {
var image = document.getElementById(imgId);
image.src = "data:image/png;base64," + evt.target.result; //You must specify the image format: png, gif, ...
};
reader.readAsDataURL(file);
}
, fail);
}
, fail);
}
, fail);
}
function fail(evt) {
console.log(evt.target.error.code);
}
Then, to load an image for a img
node with id="contact1"
:
loadImage("contact1", "/var/folders/45/xfgjqr4j59144x8gzq4gdrpw0000gn/T/photo_004.jpg");
It's just a vague idea, I haven't tested it yet.
来源:https://stackoverflow.com/questions/21045480/how-to-read-and-display-native-contact-list-photo-using-phonegap