angular6 - 如何在 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 的后端的数据库中。
解决方案
您正在使用返回的 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 中,您需要为所有已声明的变量进行显式类型化,因此您需要显式声明您需要声明您的java
和android
变量。
// 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
如上所示声明您的变量
推荐阅读
- ios - 多个音频同时播放问题
- python - Numpy拆分矩阵并将块放入对角矩阵
- vim - Vim/Nvim:背景不透明度
- ios - 具有多个触发器的 Apple 服务器到服务器通知
- react-native - React native - 如何做这样的过渡动画?
- javascript - 覆盖由 facebook 像素初始化的窗口函数 fbq
- r - 在 r 中加入多个数据帧
- javascript - 二进制搜索并插入到已排序的对象数组
- node.js - 为什么我在 Heroku nodejs 托管中收到此错误?
- javascript - 为什么我对 powerset 问题的解决方案不正确?我已经包含了我的递归和迭代方法