【问题标题】:BASE64 plugin not working in ionic 3BASE64 插件在 ionic 3 中不起作用
【发布时间】:2017-12-26 18:34:52
【问题描述】:

我需要将图像转换为从相机或图库中捕获的 base 64 格式,然后将该字符串发送到我的 REST Api。我尝试了很多方法,但我遇到的最稳定的解决方案是使用 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.');
    });

【问题讨论】:

  • 在CameraOptions中,destinationType: this.camera.DestinationType.DATA_URL return 返回图片为base64编码字符串
  • 我需要在视图上显示该图像,因此我无法在获取它时将其设为 base64。
  • 您还可以通过传递<img src="dataURLImage" 以目标类型this.camera.DestinationType.DATA_URL 在视图中显示您选择的图像
  • 请通过代码 sn-p 告诉我。我是 ionic 新手,所以我没有得到你。
  • 检查一下,我已经给出了答案。 stackoverflow.com/questions/47920164/…

标签: typescript ionic-framework ionic2 base64 ionic3


【解决方案1】:

您不需要插件进行编码,相机插件返回一个带有正确选项的 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" />

希望对你有帮助

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-04-10
    • 2020-12-26
    • 2018-02-12
    • 1970-01-01
    • 2018-02-19
    • 1970-01-01
    • 2023-03-11
    • 1970-01-01
    相关资源
    最近更新 更多