BASE64插件在离子3中不起作用



我需要将图像转换为基础64格式,然后我从相机或画廊捕获,然后将该字符串发送到我的REST API。我尝试了很多事情,但是最稳定的解决方案I遇到的是使用 Base 64 package -https://ionicframework.com/docs/native/base64/但是它都没有给我任何错误,也没有生成字符串。以下是我的代码:

  this.camera.getPicture(options).then((imagePath) => {
      this.base64.encodeFile(imagePath).then((base64Image: string) => {
        console.log(base64Image);
      }, (err) => {
        console.log(err);
        this.base64Image=err;
      });
      if (this.platform.is('android') && sourceType === this.camera.PictureSourceType.PHOTOLIBRARY) {
        this.filePath.resolveNativePath(imagePath)
          .then(filePath => {
            let correctPath = filePath.substr(0, filePath.lastIndexOf('/') + 1);
            let currentName = imagePath.substring(imagePath.lastIndexOf('/') + 1, imagePath.lastIndexOf('?'));
            this.copyFileToLocalDir(correctPath, currentName, this.createFileName());
          });
      }
      else {
        var currentName = imagePath.substr(imagePath.lastIndexOf('/') + 1);
        var correctPath = imagePath.substr(0, imagePath.lastIndexOf('/') + 1);
        this.copyFileToLocalDir(correctPath, currentName, this.createFileName());
      }
    }, (err) => {
      this.presentToast('Error while selecting image.');
    });

您不需要编码插件,相机插件返回带有正确选项的base64字符串,这是我的工作代码的一部分。

let opcoes = {
  maximumImagesCount: 1,
  sourceType: 1,
  encodingType: this.camera.EncodingType.JPEG,
  destinationType: 0, // USE THIS TO RETURN BASE64 STRING
  correctOrientation: true
};
this.camera.getPicture(opcoes).then(res => {
  this.picture= res;
  console.log('check the string', res);
  // IT RETURNS ONLY THE IMAGE STRING WITHOUT THE data:image, IF YOU WANT TO
  // SHOW YOUR PICTURE JUST APPEND THE STRING BELLOW TO YOUR RETURNED STRING AND USE IT TO DISPLAY
  this.pictureForExibition = 'data:image/jpeg;base64,' + res;
}, err => {
  console.log(err);
});

在您的html

<!-- JUST USE AN *ngIf TO CHECK IF THE PROPERTY ISN'T NULL OR IT'LL THROW ERROR FOR THE INVALID SRC -->
<img [src]="pictureForExibition" *ngIf="pictureForExibition" alt="base64 image" />

希望这有帮助

相关内容

  • 没有找到相关文章

最新更新