Search code examples
nativescriptnativescript-plugin

How can I use NativeScript 3 to capture image and send to a remote server


I'm new to NativeScript and I'm trying to capture an image with the camera module (this works fine), and convert it to base64 (this is not working) and POST to server.

I've googled for days. Any help you can lend would be immensely appreciated.

I've tried this about 16 billion different ways and this is my current code:

 viewModel.takePicture1 = function() {
    camera.requestPermissions();
    var isAvailable = camera.isAvailable(); 
    console.log(isAvailable);

    var options = { width: 640, keepAspectRatio: true, saveToGallery: false };


    camera.takePicture().then(function (img) { 
        try{
            var imageData = img.toBase64String("jpeg"); // fails here
            console.log(imageData);
        }catch(err){
            console.log("Error: "+err);
        }

        http.request({
            url: "http://[server address]/lab/ns_exp/upload_test.php",
            method: "POST",
            headers: { "Content-Type": "application/base64" },
            content: imageData
        }).then(function() { 
            console.log("Upload successful");
        }).catch(function(e) { 
            console.log("Unsuccessful upload", e);
        });
    });
}//

Oh, I do want to make clear that I'm not using angular (obviously), so please don't provide an answer that does so. : ) (Vuejs Holdout)


Solution

  • The key here is that base64 needs to know that the image is a JPEG, and what quality the image should be. The code should look like this:

    camera.takePicture(cameraOptions)
        .then(imageAsset => {
            imageSource.fromAsset(imageAsset).then(res => {
                myImageSource = res;
                var base64 = myImageSource.toBase64String("jpeg", 100);
    

    Just in case someone finds this later and wonders about putting the image (UI) and/or the image (base64) into an observableArray, here is my complete function:

    viewModel.takePhoto = function(){
        var self = this;
        camera.requestPermissions();
        var cameraOptions = { width: 640, keepAspectRatio: true, saveToGallery: false };
        camera.takePicture(cameraOptions)
        .then(imageAsset => {
            imageSource.fromAsset(imageAsset).then(res => {
                myImageSource = res;
                var base64 = myImageSource.toBase64String("jpeg", 100);
    
                self.photoData.push({"data": base64});
    
                var image = new imageModule.Image();
                image.src = imageAsset;
    
                self.photoUI.push({"src": image.src});
                listView.refresh();
            })
        }).catch(function (err) {
            console.log("Error -> " + err.message);
        });
    }