简体   繁体   中英

Nativescript get base64 data from native image

I try to use https://github.com/bradmartin/nativescript-drawingpad for saving a signature to my backend. But I am simply not capable to find a solution to get some "useful" data from getDrawing(), which returns a native image Object, for example UIImage on iOS.

I would love to "convert" the image data to some base64 (png, or whatever) string and send it to my server.

I tried someting like:

var ImageModule = require("ui/image");
var ImageSourceModule = require("image-source");

elements.drawingpad.getDrawing().then(function(a){
    var image = ImageSourceModule.fromNativeSource( a );
    api.post("sign", image.toBase64String());
});

I also tried to post simply a like seen in the demo stuff.

I would really love to see a demo of how to get my hands on the "image data" itself.

thanks!

Thanks to @bradmartin I found the solution:

var image = ImageSourceModule.fromNativeSource(a);
var base64 = image.toBase64String('png');

Actually after lots of digging with tons of error, I finally figured it out.

First you have to require the nativescript-imagepicker source module and also the nativescript image source.

var imagepicker         = require("nativescript-imagepicker");
var ImageSourceModule   = require("tns-core-modules/image-source");

a case where you want to update a user profile and also send a base64 string to your backend for processing

function changeProfileImage(args) {
    var page = args.object;
    var profile = page.getViewById("profile-avatar");
    var context = imagepicker.create({ mode: "single" });
    context.authorize().then(function() {
        return context.present();
    }).then(function(selection) {
        profile.background = `url(${selection[0]._android})`;
        profile.backgroundRepeat = `no-repeat`;
        profile.backgroundSize = `cover`;

        ImageSourceModule.fromAsset(selection[0]).then(image => {
            var base64 = image.toBase64String('png');
            // console.log(base64);
            uploadMediaFile(base64);
        });
    }).catch(function (e) {
        // process error
        console.log(e);
    });
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM