Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to take or choose image from gallery in IONIC 3

How to take an image from the gallery in IONIC 3?

I am failed to take image from gallery using

https://ionicframework.com/docs/native/camera/

https://ionicframework.com/docs/native/camera-preview/

like image 710
Somnath Avatar asked Nov 05 '17 06:11

Somnath


People also ask

How do you capture an image in ionic?

getPhoto() - that will open up the device's camera and allow us to take photos. Save the file, and if it's not running already, restart the development server in your browser by running ionic serve . On the Photo Gallery tab, click the Camera button.


2 Answers

You can do it using Native camera plugin.

.ts

 //take Photo
  takePhoto(sourceType:number) {
    const options: CameraOptions = {
      quality: 50,
      destinationType: this.camera.DestinationType.DATA_URL,
      encodingType: this.camera.EncodingType.JPEG,
      mediaType: this.camera.MediaType.PICTURE,
      correctOrientation: true,
      sourceType:sourceType,
    }

    this.camera.getPicture(options).then((imageData) => {
      let base64Image = 'data:image/jpeg;base64,' + imageData;
    }, (err) => {
      // Handle error
    });
  }

Note: You just need to call above method like:

this.takePhoto(0);//photo library

this.takePhoto(1);//camera

0 for photo library 1 for Camera

UI

enter image description here

like image 157
Sampath Avatar answered Oct 01 '22 05:10

Sampath


Following the most vote answer, a quick snippets.

Define 2 options types:

  private optionsCamera: CameraOptions = {
    quality: 100,
    targetWidth: 600,
    sourceType: this.camera.PictureSourceType.CAMERA,
    destinationType: this.camera.DestinationType.DATA_URL,
    encodingType: this.camera.EncodingType.JPEG,
    mediaType: this.camera.MediaType.PICTURE
  }

  private optionsGallery: CameraOptions = {
    quality: 100,
    sourceType: this.camera.PictureSourceType.PHOTOLIBRARY,
    destinationType: this.camera.DestinationType.DATA_URL,
    encodingType: this.camera.EncodingType.JPEG,
    mediaType: this.camera.MediaType.PICTURE
  }

and when you call you method getPicture from camera

replace options object for the proper situation.

This is for camera

this.camera.getPicture(this.optionsCamera).then((imageData) => {
  let base64Image = 'data:image/jpeg;base64,' + imageData;
 }, (err) => {
  // Handle error
  console.log(err)
 })

This is for gallery

this.camera.getPicture(this.optionsGallery).then((imageData) => {
  let base64Image = 'data:image/jpeg;base64,' + imageData;
 }, (err) => {
  // Handle error
  console.log(err)
 })
like image 32
Yoarthur Avatar answered Oct 01 '22 06:10

Yoarthur