Photo not displayed when selected from photo library in Ionic 2 - android

I am using Camera plugin in Ionic 2 for uploading photos. I am running the app on an Android device. The Carema capture is displayed in the app but when selected from Gallery the photo is not displayed.
The following methods are used for Camera and Gallary:
private openCamera(){
var options: CameraOptions = {
sourceType: this.camera.PictureSourceType.CAMERA,
destinationType: this.camera.DestinationType.DATA_URL,
allowEdit: true,
saveToPhotoAlbum: true
};
this.camera.getPicture(options).then((imageData) => {
this.cameraData = 'data:image/jpeg;base64,' + imageData;
this.photoTaken = true;
this.photoSelected = false;
let base64Image = 'data:image/jpeg;base64,' + imageData;
}, (err) => {
// Handle error
});
}
private selectFromGallery() {
var options = {
sourceType: this.camera.PictureSourceType.PHOTOLIBRARY,
destinationType: this.camera.DestinationType.FILE_URI
};
this.camera.getPicture(options).then((imageData) => {
this.cameraUrl = imageData;
this.photoSelected = true;
this.photoTaken = false;
}, (err) => {
// Handle error
});
}
Following is the code to display in HTML page:
<img [src]="cameraData" *ngIf="photoTaken">
<img [src]="cameraUrl" *ngIf="photoSelected">

You need to use a file plugin to obtain local filesystem url when you select from library.
To install:
$ ionic cordova plugin add cordova-plugin-file
$ npm install --save #ionic-native/file
Import:
import { File } from '#ionic-native/file';
and in your code:
constructor( private file: File, .... ) {}
.....
const options: CameraOptions = {
destinationType: this.camera.DestinationType.FILE_URI,
sourceType: this.camera.PictureSourceType.PHOTOLIBRARY
}
this.camera.getPicture(options).then((imageURI) => {
this.file.resolveLocalFilesystemUrl(imageURI).then(fileEntry => {
this.cameraUrl = fileEntry.nativeURL;
this.photoSelected = true;
this.photoTaken = false;
});
}, (err) => {
// Handle error
});
EDIT
You might need to sanitize the value for img src:
<img *ngIf="cameraUrl" [src]="sanitizeUrl(cameraUrl)" />
The function:
import { DomSanitizer } from '#angular/platform-browser';
....
constructor( private sanitizer: DomSanitizer, .... ) {}
....
sanitizeUrl(url) {
return this.sanitizer.bypassSecurityTrustUrl(url);
}

Related

Uploading Image from android file system to Firebase Storage

I am currently creating a page that allows users to take pictures of both their identity card and selfie of themselves, however, i am not able to get the files from the file system to upload it using submitpicture().
Here is my typescript code:
import { Component, OnInit } from '#angular/core';
import { File } from '#ionic-native/file/ngx';
import { Camera, CameraOptions } from '#ionic-native/camera/ngx';
import * as firebase from 'firebase';
import { EmailComposer } from '#ionic-native/email-composer/ngx';
import { ModalController } from '#ionic/angular';
#Component({
selector: 'app-verifyidentity',
templateUrl: './verifyidentity.page.html',
styleUrls: ['./verifyidentity.page.scss'],
})
export class VerifyidentityPage implements OnInit {
constructor(public camera: Camera, public file: File, private modalController: ModalController, public emailComposer: EmailComposer) { }
nric: any;
selfie: any;
nricimageData: any;
selfieimageData: any;
ngOnInit() {
}
takenric() {
const options: CameraOptions = {
quality: 100,
destinationType: this.camera.DestinationType.FILE_URI,
encodingType: this.camera.EncodingType.JPEG,
mediaType: this.camera.MediaType.PICTURE,
saveToPhotoAlbum: true,
cameraDirection: 1
}
this.camera.getPicture().then((imageData) => {
this.nricimageData = imageData
let filename = imageData.substring(imageData.lastIndexOf('/') + 1);
let path = imageData.substring(0, imageData.lastIndexOf('/') + 1);
this.file.readAsDataURL(path,filename).then((base64data) => {
this.nric = base64data;
firebase.storage().ref().child("test").put(imageData).then(snapshot => {
console.log('Uploaded image ');
});
})
});
}
takeselfie() {
const options: CameraOptions = {
quality: 100,
destinationType: this.camera.DestinationType.FILE_URI,
encodingType: this.camera.EncodingType.JPEG,
mediaType: this.camera.MediaType.PICTURE,
saveToPhotoAlbum: true,
cameraDirection: 1
}
this.camera.getPicture().then((imageData) => {
this.selfieimageData = imageData
let filename = imageData.substring(imageData.lastIndexOf('/') + 1);
let path = imageData.substring(0, imageData.lastIndexOf('/') + 1);
this.file.readAsDataURL(path,filename).then((base64data) => {
this.selfie = base64data;
firebase.storage().ref().child("test").put(imageData).then(snapshot => {
console.log('Uploaded image ');
});
})
});
}
submitpicture() {
firebase.storage().ref().child("nric").put(this.nric); // this does not work!
}
I was wondering if it is possible to get the image from the android system with the file path and store it in a variable before uploading to firebase storage with submitpicture().
So sorry for any inconvenience caused and thank you.
Best regards,
Dan

ionic 4 (android) get image (OBJECT FILE) from gallery (FILE_URI) and upload via API

I'm trying to implement a simple application using Ionic v4 angular and cordova. Just select a photo and upload it to a parse server (back4app.com). But I couldn't do it.
This is my code:
home.page.ts
import { ParseService } from '../service/parse.service';
import { Camera, CameraOptions } from '#ionic-native/camera/ngx';
import { File } from '#ionic-native/file/ngx';
import { WebView } from '#ionic-native/ionic-webview/ngx';
selectPhoto() {
const options: CameraOptions = {
quality: 100,
sourceType: this.camera.PictureSourceType.PHOTOLIBRARY,
destinationType: this.camera.DestinationType.FILE_URI,
encodingType: this.camera.EncodingType.JPEG,
mediaType: this.camera.MediaType.PICTURE,
correctOrientation: true
}
this.camera.getPicture(options).then((imageData) => {
// imageData is either a base64 encoded string or a file URI
// If it's base64 (DATA_URL):
// let base64Image = 'data:image/jpeg;base64,' + imageData;
// console.log(imageData);
this.fileToUpload = imageData;
this.phototoshow = this.webview.convertFileSrc(imageData);
}, (err) => {
// Handle error
});
}
onSubmit() {
this.presentLoading();
// return this.apiService.upload(this.phototoshow).subscribe((data: any) => {
return this.apiService.upload(this.fileToUpload).subscribe((data: any) => {
console.log(data);
}
}
service.ts
upload(img1): Observable<any> {
// console.log(data);
return this.http.post(this.apiURL + '/files/img.jpg', img1,{
headers: {
'X-Parse-Application-Id': this.APP_ID,
'X-Parse-REST-API-Key': this.REST_API_KEY,
'Content-Type':'image/jpeg'
}
})
.pipe(
retry(1),
catchError(this.handleError)
)
}
I was able to upload the image with "input type = file" in the form ... but selecting the image from the gallery with the cordova plugin camera ... it only returns FILE_URI but I need the OBJECT FILE to upload via api rest.
I have read enough info on the web but it is old information that does not help me. I hope someone can help me with the problem. thanks
I managed to solve the problem:
startUpload() {
this.file.resolveLocalFilesystemUrl(this.fileToUpload)
// this.file.resolveLocalFilesystemUrl(imgEntry.filePath)
.then(entry => {
(entry as FileEntry).file(file => this.readFile(file))
})
.catch(err => {
alert('Error while reading file.');
});
}
readFile(file: any) {
const reader = new FileReader();
reader.onload = () => {
const imgBlob = new Blob([reader.result], {
type: file.type
});
this.onSubmit(imgBlob);
};
reader.readAsArrayBuffer(file);
}

Ionic 4 - Native camera plugin issues

I have developed an android application using Ionic4. I am facing some issues with Ionic Native Camera plugin. The following is my code. The issues that i am facing is given below. The version if camera plugin i am using is "#ionic-native/camera": "^5.3.0",.
Issues
Gallery is not opening
Captured image is not returning.
Application crashes after taking picture
html
<img [src]="studentImage!==null ? studentImage: 'assets/icon/ic_avatar.png'" class="add-picture" (click)="addImage()">
.ts
public addImage() {
this.genericServices.presentActionSheet(this.openGallery, this.openCamera);
}
private openCamera = () => {
this.studentImage = this.genericServices.selectPicture('camera');
console.log('Captured Image:=>' + this.studentImage);
}
private openGallery() {
this.studentImage = this.genericServices.selectPicture('gallery');
}
service
public async selectPicture(source) {
let base64Image = null;
const cameraOptions: CameraOptions = {
quality: 75,
destinationType: this.camera.DestinationType.DATA_URL,
encodingType: this.camera.EncodingType.PNG,
mediaType: this.camera.MediaType.PICTURE,
sourceType: source === 'camera' ? this.camera.PictureSourceType.CAMERA : this.camera.PictureSourceType.PHOTOLIBRARY,
correctOrientation: true
};
await this.camera.getPicture(cameraOptions).then((imageData) => {
console.log('Returned Image=>' + base64Image);
return base64Image = 'data:image/jpeg;base64,' + imageData;
}).catch(() => {
});
}
Hard to say what your problem is. I would probably write the code slightly different, like this:
async selectImage() {
const actionSheet = await this.actionCtrl.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();
}
And then in the takePicture() method decide what destinationType should be, default is FILE_URI (1).
takePicture(sourceType: PictureSourceType) {
var options: CameraOptions = {
quality: 80,
sourceType: sourceType,
saveToPhotoAlbum: false,
correctOrientation: true,
destinationType: 1,
targetWidth: 1240,
targetHeight: 768,
};
this.camera.getPicture(options)
.then((imageData) => {
// do something with the imageData, should be able to bind it to a variable and
// show it in your html file. You might need to fix file path,
// remember to import private win: any = window, and use it like this.
this.imagePreview = this.win.Ionic.WebView.convertFileSrc(imageData);
}).catch((err) => {
console.warn("takePicture Error: " + err);
});
}
This should work fine... i just tested it. But as i said, there could be several things wrong with your setup. Hope it helps in one way or another... otherwise create a fiddle, and i will gladly look at the code for you.

Not allowed to load local resource: ionic 3 android

I am using ionic 3 android build apk and trying to laod image from file:///storage/emulated/0/data/io.ionic.vdeovalet/cache/image.jpeg
takePicture(sourceType) {
try {
// Create options for the Camera Dialog
var options = {
quality: 100,
destinationType: this.camera.DestinationType.FILE_URI,
encodingType: this.camera.EncodingType.JPEG,
sourceType: sourceType,
};
this.camera.getPicture(options).then((imagePath) => {
// Special handling for Android library
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());
this.lastImage = filePath;
});
} 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.');
});
} catch (e) {
console.error(e);
}
}
Error: Not allowed to load local resource
android 6.0.1
No Need To Downgrade just write this code.
private win: any = window;
this.win.Ionic.WebView.convertFileSrc(path);
I had the same issues and it turns out that
The new ionic webview plugin is the cause for the problem.
The new plugin: cordova-plugin-ionic-webview # 2.x seem unstable...
to get it working downgraded back to cordova-plugin-ionic-webview#1.2.1 and all should work
Steps:
1. uninstall webview
ionic cordova plugins rm cordova-plugin-ionic-webview
2. install old one:
ionic cordova plugins add cordova-plugin-ionic-webview#1.2.1
3. clean cordova
cordova clean android
When Ionic is used with Capacitor, we can get the correct path of an image or other resource on a native device by:
import { Capacitor } from '#capacitor/core';
Capacitor.convertFileSrc(filePath);
https://ionicframework.com/docs/core-concepts/webview
The only thing that worked for me was convertFileSrc()
let win: any = window;
let safeURL = win.Ionic.WebView.convertFileSrc(this.file.dataDirectory+'data/yourFile.png');
Hope this helps
Try This:
1) https://devdactic.com/ionic-2-images/
In this tutorial, ionic 2 & ionic 3 is the best way to upload and upload images.
2) https://devdactic.com/ionic-4-image-upload-storage/ In this tutorial, ionic 4 is the best way to upload and upload images.
i also use these... and it working fine...
And I have also faced the problem of
not allowed to load local resource
You can see here :
#ionic/angular 4.0.0-beta.13 : Not allowed to load local resource : with webview 2.2.3 - Ionic CLI 4.3.1
Try this:
const options: CameraOptions = {
quality: 10
, destinationType: this.camera.DestinationType.DATA_URL
, mediaType: this.camera.MediaType.PICTURE
// Optional , correctOrientation: true
, sourceType: sourceType == 0 ? this.camera.PictureSourceType.CAMERA : this.camera.PictureSourceType.PHOTOLIBRARY
// Optional , saveToPhotoAlbum: true
};
this.camera.getPicture(options).then(imageBase64 => {
let txtForImage = `data:image/jpeg;base64,` + imageBase64;
this.imageToLoad = txtForImage;
})
.catch(error => {
alert("Error: " + error);
console.error(error);
});
Copy this line into your index.html
<meta http-equiv="Content-Security-Policy" content="default-src *;
style-src 'self' 'unsafe-inline';
script-src 'self' 'unsafe-inline' 'unsafe-eval';
img-src 'self' data: https://s-media-cache-ak0.pinimg.com;
script-src 'self' https://maps.googleapis.com;" />
Then, write this function instead of your one, note that what this script does is returning the photo as base64
getImageFromCamera() {
const options: CameraOptions = {
quality: 20,
saveToPhotoAlbum: true,
destinationType: this.camera.DestinationType.FILE_URI,
sourceType: this.camera.PictureSourceType.CAMERA,
encodingType: this.camera.EncodingType.JPEG,
allowEdit: false
};
this.camera.getPicture(options).then((imageData) => {
this.imageURI = imageData;
this.imageName = imageData.substr(imageData.lastIndexOf('/') + 1);
// Create a folder in memory location
this.file.checkDir(this.file.externalRootDirectory, 'Demo')
.then(() => {
this.fileCreated = true;
}, (err) => {
console.log("checkDir: Error");
this.presentToast("checkDir Failed");
});
if (this.fileCreated) {
this.presentToast("Directory Already exist");
}
else {
this.file.createDir(this.file.externalRootDirectory, "Demo", true)
.then((res) => {
this.presentToast("Directory Created");
}, (err) => {
console.log("Directory Creation Error:");
});
}
//FILE MOVE CODE
let tempPath = this.imageURI.substr(0, this.imageURI.lastIndexOf('/') + 1);
let androidPath = this.file.externalRootDirectory + '/Bexel/';
this.imageString = androidPath + this.imageName;
this.file.moveFile(tempPath, this.imageName, androidPath, this.imageName)
.then((res) => {
this.presentToast("Image Saved Successfully");
this.readImage(this.imageString);
}, (err) => {
console.log("Image Copy Failed");
this.presentToast("Image Copy Failed");
});
//Complete File Move Code
this.toDataURL(this.imageURI, function (dataUrl) {
console.log('RESULT:' + dataUrl);
});
}, (err) => {
console.log(JSON.stringify(err));
this.presentToast(JSON.stringify(err));
});
}
presentToast(msg) {
let toast = this.toastCtrl.create({
message: msg,
duration: 2000
});
toast.present();
}
toDataURL(url, callback) {
let xhr = new XMLHttpRequest();
xhr.onload = function () {
let reader = new FileReader();
reader.onloadend = function () {
callback(reader.result);
};
reader.readAsDataURL(xhr.response);
};
xhr.open('GET', url);
xhr.responseType = 'blob';
xhr.send();
}
readImage(filePath) {
let tempPath = filePath.substr(0, filePath.lastIndexOf('/') + 1);
let imageName = filePath.substr(filePath.lastIndexOf('/') + 1);
this.file.readAsDataURL(tempPath, imageName)
.then((res) => {
this.presentToast("Image Get Done");
this.imageUrl = res;
}, (err) => {
this.presentToast("Image Get Error");
});
}
It sees like it's an issue with content CSP (content security policy), the meta tag should fix this issue, then the code will read the photo as base64, then here you go, in HTML:
<img [src]="imageUrl">
And you can modify the function to remove unnecessary console.log, i was just testing.
All I had to do was use the proper Imagepicker Options, the output type did it:
const options: ImagePickerOptions = {
maximumImagesCount: 1,
outputType: 1,
quality: 50
};
let win: any = window; // hack ionic/angular compilator
var myURL = win.Ionic.WebView.convertFileSrc(myURL);

how to launch camera in an ionic app

I have created the basic ionic app which can launch camera. I installed all the required plugins and also i have used the right version of cordova . I am not getting any errors and also able to create apk for that . When using in apk in the android mobile, camera is not getting launched.
this is the home.html code adding camera module
<button ion-button (click)="takePhoto()">camera</button>
<p align="center"><img src="{{ myphoto }}"></p>
this is the home.ts file
import { Component } from '#angular/core';
import { NavController } from 'ionic-angular';
import { Camera, CameraOptions } from '#ionic-native/camera';
import { Database } from '../../providers/database/database';
#Component({
selector: 'page-home',
templateUrl: 'home.html'
})
export class HomePage {
tabBarElement: any;
splash = true;
myphoto:any;
public hasTrees : boolean = false;
public trees : any;
constructor(public navCtrl: NavController, private camera:Camera,
public DB : Database) {
this.tabBarElement = document.querySelector('.tabbar');
}
takePhoto(){
const options: CameraOptions = {
quality: 70,
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.myphoto = 'data:image/jpeg;base64,' + imageData;
}, (err) => {
// Handle error
});
}
ionViewDidLoad() {
this.tabBarElement.style.display = 'none';
setTimeout(() => {
this.splash = false;
this.tabBarElement.style.display = 'flex';
}, 4000);
}
ionViewWillEnter()
{
this.displayTrees();
}
displayTrees()
{
this.DB.retrieveTrees().then((data)=>
{
let existingData = Object.keys(data).length;
if(existingData !== 0)
{
this.hasTrees = true;
this.trees = data;
}
else
{
console.log("we get nada!");
}
});
}
addSpecies()
{
this.navCtrl.push('Add');
}
viewSpecies(param)
{
this.navCtrl.push('Add', param);
}
}

Categories

Resources