Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Displaying image taken from camera

As you can see below, I am using the [src] attribute. What I am trying to do is preview the image taken from a device's camera. Please see the rest of the typescript code below.

<img [src]="lastImage" style="width: 100%" [hidden]="lastImage === null">
<button ion-button icon-left (click)="presentActionSheet()">
    <ion-icon name="camera"></ion-icon>Select Image
</button>

Here is .ts code

lastImage: string = null;

public presentActionSheet() {
    let actionSheet = this.actionSheetCtrl.create({
        title: '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'
            }
        ]
    });

    actionSheet.present();
}

public takePicture(sourceType) {
    // Create options for the Camera Dialog
    var options = {
        quality: 100,
        sourceType: sourceType,
        saveToPhotoAlbum: false,
        correctOrientation: true
    };

    // Get the data of an image
    this.camera.getPicture(options).then((imagePath) => {
        // Special handling for Android library
        if (this.platform.is('ios') && sourceType === this.camera.PictureSourceType.PHOTOLIBRARY) {
            alert('IF');
            this.filePath.resolveNativePath(imagePath).then(filePath => {
                let correctPath = filePath.substr(0, filePath.lastIndexOf('/') + 1);
                let currentName = imagePath.substring(imagePath.lastIndexOf('/') + 1, imagePath.lastIndexOf('?'));

                // alert(correctPath);
                alert(correctPath + currentName);
                this.lastImage = correctPath + currentName;
                // this.copyFileToLocalDir(correctPath, currentName, this.createFileName());
            });
        } else {
            alert('ELSE'); // This part runs
            var currentName = imagePath.substr(imagePath.lastIndexOf('/') + 1);
            var correctPath = imagePath.substr(0, imagePath.lastIndexOf('/') + 1);

            alert(cordova.file.dataDirectory + currentName); // This returns proper image path

            this.lastImage = cordova.file.dataDirectory + currentName;

            alert(this.lastImage); // this also has the image path.

            this.copyFileToLocalDir(correctPath, currentName, this.createFileName());
        }
    }, (err) => {
        this.presentToast('Error while selecting image.');
    });
}

Now when I choose image Use Camera then it opens the camera and I take a photo. But somehow the photo is not previewed in my above HTML where I am using [src]="lastImage". What is wrong with my code that it does not show any image from the camera?

UPDATE

I also used normalizeURL which I found here like following!

import { normalizeURL } from 'ionic-angular';

this.lastImage = normalizeURL(cordova.file.dataDirectory + currentName);

What happens with this piece of code is that it replaces file:/// part with http://localhost:8080 whereas I am taking a photo from the camera which local not any server and want to display that on img tag.

like image 743
null Avatar asked Apr 06 '18 01:04

null


4 Answers

He, I suggest that use base64 to set image to img tag, check the next code:

Controller atribute

private base64Image: any = false;

In your controller constructor set: "public domSanitizer: DomSanitizer" as parameter, this allow say to angular that the image is "safe".

Controller method

takePicture() {

const options: CameraOptions = {
  quality: 10,
  destinationType: this.camera.DestinationType.DATA_URL,
  encodingType: this.camera.EncodingType.JPEG,
  mediaType: this.camera.MediaType.PICTURE
}

this.camera.getPicture(options).then((imageData) => {
  // imageData is either a base64 encoded string or a file URI
  // If it's base64:
  this.base64Image = 'data:image/jpeg;base64,' + imageData;

}, (err) => {
  this.message("Error, your camera device not work");
});

}

In your view file

<img *ngIf="base64Image != 'false'" [src]="domSanitizer.bypassSecurityTrustUrl(base64Image)">
like image 65
Yoandy Pérez Villazón Avatar answered Sep 28 '22 00:09

Yoandy Pérez Villazón


import { normalizeURL } from 'ionic-angular';

<img *ngIf="base64Image" src="{{base64Image}}"/> 
   openCamera(pictureSourceType: any) {
let options: CameraOptions = {
  quality: 95,
  destinationType: this.camera.DestinationType.FILE_URI,
  sourceType: pictureSourceType,
  encodingType: this.camera.EncodingType.PNG,
  targetWidth: 400,
  targetHeight: 400,
  saveToPhotoAlbum: true,
  correctOrientation: true
};
this.camera.getPicture(options).then(imageData => {
    if (this.platform.is('ios'))
    this.base64Image = normalizeURL(imageData);
     // IF problem only occur in ios and normalizeURL 
     //not work for you then you can also use 
     //this.base64Image= imageData.replace(/^file:\/\//, '');
  else
    this.base64Image= "data:image/jpeg;base64," + imageData;
}, error => {
  console.log('ERROR -> ' + JSON.stringify(error));
});
}
like image 39
Manoj Bhardwaj Avatar answered Sep 28 '22 00:09

Manoj Bhardwaj


in my case, when i'm setting src to image tag in my localhost it is giving some unsafe security issue ERR_UNKNOWN_URL_SCHEME.

so i used DomSanitizer to bypassSecurity like below.

constructor(private senitizer: DomSanitizer) {}

this.imageUrl = <string>this.senitizer.bypassSecurityTrustUrl(this.imageUrl);

so check your console and if there is same problem, then instead of 'normalizeURL' use above code to bypass security for localhost.

or if you deploy your code on some secure domain (https), it does not require security bypass.

like image 34
Ravi Sevta Avatar answered Sep 28 '22 01:09

Ravi Sevta


Probably it passes the LOCATION to the src (instead of URL). You can:

1) Move the picture file (i.e from C:/path/file.jpg ) into the LOCALHOST's www root folder and use url http://localhost/file.jpg in src attribute.

or

2) convert/append image to <canvas> element ( but learn some basics of that)

or

3) As advised already, convert image to BASE64 string (not nice way, but works) and append the data to src.

like image 27
T.Todua Avatar answered Sep 28 '22 00:09

T.Todua