我是Ionic的新手,我正尝试将图像发送到要求base64编码的API,当我从Ionic相机插件拍摄照片时,编码无法正常工作,因为它为我提供了缓存路径,但是我能够检索到使用文件阅读器生成的图片,我的代码如下
HTML文件
<button ion-button round (click)="takePicture()">Take a Picture</button>
Uploaded Picture:
<img [src]=[base64Image] *ngIf="base64Image" />
TS文件
takePicture(){
this.content.scrollToBottom(200);
let options = {
destinationType: this.camera.DestinationType.NATIVE_URI,
targetWidth: 300,
targetHeight: 300,
quality: 100,
allowEdit: false,
correctOrientation: false,
saveToPhotoAlbum: true
};
this.camera.getPicture(options)
.then((imageData)=>{
console.log(imageData);
this.base64Image = "data:image/jpeg;base64,"+imageData;
})
.catch(err=>{
console.log(err);
})
}
当我使用文件读取器尝试相同的操作时,
onFileChange(event) {
if (event.target.files && event.target.files[0]) {
var reader = new FileReader();
reader.onload = (event: ProgressEvent) => {
this.base64 = (<FileReader>event.target).result;
console.log(event.target);
}
reader.readAsDataURL(event.target.files[0]);
console.log(event.target.files[0]);
}
}
HTML文件
<input type="file" id="lic" name="lic" (change)="onFileChange($event)" capture="camera" accept="image/*"/>
<button ion-button round (click)="licensify()">Upload</button>
答案 0 :(得分:0)
您可以使用Camera.DestinationType:DATA_URL,这将在getPicture Promise中返回一个“ base64编码的字符串”。
因此您的ts文件应如下所示
takePicture(){
this.content.scrollToBottom(200);
let options = {
destinationType: this.camera.DestinationType.DATA_URL,
targetWidth: 300,
targetHeight: 300,
quality: 100,
allowEdit: false,
correctOrientation: false,
saveToPhotoAlbum: true
};
this.camera.getPicture(options)
.then((imageData)=>{
console.log(imageData);
//base64 encoded string
this.base64Image = "data:image/jpeg;base64,"+imageData;
})
.catch(err=>{
console.log(err);
})
}