Сбор изображений из PhotoLibrary не работает - Ionic 4 - PullRequest
0 голосов
/ 20 января 2019

Я реализую функцию загрузки изображений в свое приложение, которое я разрабатываю с помощью Ionic 4. Я использую встроенную камеру плагина и несколько других для выполнения следующих действий:

async selectImage() {
    const actionSheet = await this.actionsheet.create({
      header: "Select Image source",
      buttons: [{
        text: 'Load from Library',
        handler: () => {
          this.takePicture(this.camera.PictureSourceType.PHOTOLIBRARY);
        }
      },
      {
        text: 'Use Camera',
        handler: () => {
          this.takePicture(this.camera.PictureSourceType.CAMERA);
        }
      },
      {
        text: 'Cancel',
        role: 'cancel'
      }
      ]
    });
    await actionSheet.present();
  }

  takePicture(sourceType: PictureSourceType) {
    var options: CameraOptions = {
      quality: 100,
      sourceType: sourceType,
      saveToPhotoAlbum: false,
      correctOrientation: true
    };

    this.camera.getPicture(options).then(imagePath => {
      var currentName = imagePath.substr(imagePath.lastIndexOf('/') + 1);
      var correctPath = imagePath.substr(0, imagePath.lastIndexOf('/') + 1);
      this.copyFileToLocalDir(correctPath, currentName, this.createFileName());
    });
  }

  copyFileToLocalDir(namePath, currentName, newFileName) {
    this.file.copyFile(namePath, currentName, this.file.dataDirectory, newFileName).then(success => {
      this.presentToast('Dispongo a actualizar.');
      this.updateStoredImages(newFileName);
    }, error => {
     // this.presentToast('Error while storing file.');
    });
  }
  updateStoredImages(name) {
    this.storage.get(STORAGE_KEY).then(images => {
      let arr = JSON.parse(images);
      if (!arr) {
        let newImages = [name];
        this.storage.set(STORAGE_KEY, JSON.stringify(newImages));
      } else {
        arr.push(name);
        this.storage.set(STORAGE_KEY, JSON.stringify(arr));
      }

      let filePath = this.file.dataDirectory + name;
      let resPath = this.pathForImage(filePath);

      let newEntry = {
        name: name,
        path: resPath,
        filePath: filePath
      };

      this.images = [newEntry, ...this.images];
      this.ref.detectChanges(); // trigger change detection cycle
    });
  }

Итак, на листе действий, когда я нажимаю первую опцию (Загрузить из библиотеки), она открывает библиотеку, и я могу без труда выбрать изображение. Когда я нажимаю ok , выдается ошибка: ошибка, ожидаемая от copyFileToLocalDir. Однако, если я сделаю то же самое со вторым параметром («Использовать камеру») и сделаю снимок с помощью камеры, он отлично загружается, и я могу сохранить его позже.

Я не могу найти проблему, пожалуйста, помогите.

1 Ответ

0 голосов
/ 20 января 2019

Я использую этот код, используя ionic 3, и он работает нормально. и после того, как я выберу одно изображение, оно будет загружено в Firebase и в то же время просмотреть его на странице .html

app.module.ts Вы должны импортировать

import { Camera } from "@ionic-native/camera";
import { File } from "@ionic-native/file";

и добавил их @providers затем используйте этот код в page.ts, который вы выберете одно изображение:

просмотр html

<button ion-button full (click)="openGallery()">open gallery</button>
<img [src]="camel_profile_image_path" />

ts page

import { Camera, CameraOptions } from "@ionic-native/camera";
private camera: Camera,

async openGallery() {
try {
  const opstions: CameraOptions = {
    quality: 100,
    targetHeight: 600,
    targetWidth: 600,
    destinationType: this.camera.DestinationType.DATA_URL,
    encodingType: this.camera.EncodingType.JPEG,
    mediaType: this.camera.MediaType.PICTURE,
    sourceType: this.camera.PictureSourceType.PHOTOLIBRARY,
    correctOrientation: true
  }

  const result = await this.camera.getPicture(opstions);
  const image = 'data:image/jpeg;base64,' + result;
  const pictures = storage().ref('Profile Images/' + this.randomNumber + '.jpg');
  pictures.putString(image, 'data_url');
  this.base64Image = image;
  this.camel_profile_image_path = this.randomNumber; // view the image on html page 
  this.slidetothis();
} catch (error) {
  console.error(error);
}

}

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...