Skip to content

Instantly share code, notes, and snippets.

@pamelafox
Created March 23, 2012 18:32
Show Gist options
  • Save pamelafox/2173589 to your computer and use it in GitHub Desktop.
Save pamelafox/2173589 to your computer and use it in GitHub Desktop.
PhoneGap Convert Photo File URI to Data URI
function getPhoto() {
navigator.camera.getPicture(onPhotoSuccess, onPhotoFail,
{quality: 70, targetWidth: 500, targetHeight: 500,
sourceType: navigator.camera.SourceType.PHOTOLIBRARY,
destinationType: navigator.camera.DestinationType.FILE_URI,
});
}
function onPhotoSuccess(imageUri) {
var $img = $('<img/>');
$img.attr('src', imageUri);
$img.css({position: 'absolute', left: '0px', top: '-999999em', maxWidth: 'none', width: 'auto', height: 'auto'});
$img.bind('load', function() {
var canvas = document.createElement("canvas");
canvas.width = $img.width();
canvas.height = $img.height();
var ctx = canvas.getContext('2d');
ctx.drawImage($img[0], 0, 0);
var dataUri = canvas.toDataURL('image/png');
$mealImg.attr('src', 'data:image/png;base64,' + imageDataUri);
});
$img.bind('error', function() {
console.log('Couldnt convert photo to data URI');
});
$('body').append($img);
}
function onPhotoFail(message) {
console.log(message);
}
@m-misseri
Copy link

@itsasad
Copy link

itsasad commented Apr 24, 2014

also $mealImg need to change to $img

@manojrejinthala
Copy link

i have tried code its very good to understand but i am getting dataUri as data:,Could you please suggest me

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