我是NativeScript的新手,我试图使用相机模块捕获图像(这很好),并将其转换为base64(这不起作用)和POST到服务器。
我用Google搜索了好几天。任何你可以借出的帮助都会非常感激。
我已经尝试了大约160亿种不同的方式,这是我目前的代码:
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);
});
});
}//
哦,我确实想说明我没有使用角度(显然),所以请不要提供这样做的答案。 :)(Vuejs Holdout)
答案 0 :(得分:0)
这里的关键是base64需要知道图像是JPEG,图像应该是什么质量。代码应如下所示:
camera.takePicture(cameraOptions)
.then(imageAsset => {
imageSource.fromAsset(imageAsset).then(res => {
myImageSource = res;
var base64 = myImageSource.toBase64String("jpeg", 100);
以防有人后来发现这个并想知道将图像(UI)和/或图像(base64)放入observableArray中,这是我的完整功能:
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);
});
}