prime February 2016

Convert image into base64string in visualstudio apache cordova

I am working on VS2015 cordova app .I have a problem when i get image from gallery and corverting it into base64string . I got the base64string successfully but when i dispalayed it I always get black image . here is my code :

    function onPhotoURISuccess(imageURI) {
     var largeImage = document.getElementById('smallImage');
    largeImage.style.display = 'block';
    largeImage.src = imageURI;
    basestrg = encodeImageUri(imageURI);

}

function getPhoto(source) {
           navigator.camera.getPicture(onPhotoURISuccess, onFail, {
        destinationType: Camera.DestinationType.NATIVE_URI, mediaType: Camera.MediaType.Photo,
        sourceType: source
    });
}
function encodeImageUri(imageUri) {
    var c = document.createElement('canvas');
    var ctx = c.getContext("2d");
    var img = new Image();
    img.onload = function () {
        c.width = this.width;
        c.height = this.height;
        ctx.drawImage(img, 0, 0);
    };
    img.src = imageUri;
    var dataURL = c.toDataURL("image/jpeg");
    return dataURL;
}

any ideas

Answers


Jordan Matthiesen February 2016

I tried to get your specific code working, but I saw the same end result with the black box.

I think there's an easier way to achieve your goal, though. Instead of passing in NATIVE_URI as the destination type, there's an option called DATA_URL that you can use. This DATA_URL option will provide you the base64 encoded string that you may then use in the image element.

Here's a some code that worked for me when I placed it in your getPhoto() function. I adapted this from the Cordova Camera Plugin Documentation:

navigator.camera.getPicture(onSuccess, onFail, {
    destinationType: Camera.DestinationType.DATA_URL,
    mediaType: Camera.MediaType.PICTURE,
    sourceType: source
});

function onSuccess(imageData) {
    var image: any = document.getElementById('myPicture');
    image.src = "data:image/jpeg;base64," + imageData;
}

function onFail(message) {
    alert('Failed because: ' + message);
}

Post Status

Asked in February 2016
Viewed 2,715 times
Voted 5
Answered 1 times

Search




Leave an answer