首页 > 解决方案 > 如何在 nativescript 中将图像路径转换为 ​​base64?

问题描述

我正在使用 nativescript 并且无法在本地脚本中将本地图像路径转换为 ​​base 64。

private startSelection(context) {

    let that = this;  

    context
    .authorize()
    .then(() => {
        that.imageAssets = [];
        that.imageSrc = null;
        return context.present();
    })
    .then((selection) => {

        //console.log("Selection done: " + JSON.stringify(selection));
        that.imageSrc = that.isSingleMode && selection.length > 0 ? selection[0] : null;
        //console.log( "Hello skdafyvsoa ydfs98a698d8s9" + JSON.stringify(that.imageSrc)); 

       // var base64 = that.imageSrc._android.toBase64String();
        // var base64 = that.imageSrc._android;
        const image = that.imageSrc._android;
        //const imageAsBase64 = image.toBase64String(enums.ImageFormat.png);
        //var data = base64Img.base64Sync(image);
        // console.log(data);

        // set the images to be loaded from the assets with optimal sizes (optimize memory usage)
        selection.forEach(function (element) {
            element.options.width = that.isSingleMode ? that.previewSize : that.thumbSize;
            element.options.height = that.isSingleMode ? that.previewSize : that.thumbSize;
        });

        that.imageAssets = selection;
        this.checkFileupload = true; 
    }).catch(function (e) {
        console.log(e);
    });
}

请帮助此代码

_handleReaderLoaded(readerEvt) {
    var binaryString = readerEvt.target.result;

    console.log(binaryString);
           this.base64textString= btoa(binaryString);
           console.log(btoa(binaryString));
   }

我正在使用带有本机脚本的 Angular 6,并且想要将图像转换为 base64 并保存到我正在使用 sql server 的后端的数据库中。

标签: angular6nativescriptnativescript-angular

解决方案


您正在使用返回的 nativescript-imagepicker 插件ImageAsset。如评论中所述,您收到的路径不是对图像的直接引用。因此,要发送实际图像的 base64 表示,您需要创建它然后对其进行解码。这是在Android上的操作方法。

selection.forEach(element => {
      let asset: ImageAsset = element;

      // if Android
      asset.getImageAsync((bitmap) => {
          console.log(`android.graphics.Bitmap: ${bitmap}`);

          let byteArrayOutputStream = new java.io.ByteArrayOutputStream();
          bitmap.compress(android.graphics.Bitmap.CompressFormat.PNG, 100, byteArrayOutputStream);
          let byteArray = byteArrayOutputStream.toByteArray();
          console.log(`byteArray: ${byteArray}`); // BASE64
    });
});

请注意,我正在访问本机 Android API 和 java 命名空间。在 TypeScript 中,您需要为所有已声明的变量进行显式类型化,因此您需要显式声明您需要声明您的javaandroid变量。

// somewhere at the beginning of the file
declare let android: any; // or use tns-platform-declarations
declare let java: any;

对于 Android 和 iOS API,您还可以使用ns-platform-declarations(这是更好和推荐的方法),但您仍然需要java如上所示声明您的变量


推荐阅读