We need to load photos from camera or library(photo-gallery) and upload it.
In Android device working fine but iOS has a below error:
TypeError: Object(WEBPACK_IMPORTED_MODULE_1__ionic_native_core["cordova"]) is not a function. (In 'Object(WEBPACK_IMPORTED_MODULE_1__ionic_native_core["cordova"])(this, "getPicture", { "callbackOrder": "reverse" }, arguments)', 'Object(WEBPACK_IMPORTED_MODULE_1__ionic_native_core["cordova"])' is an instance of Object)
Also, For more details see attached screenshot.
enter image description here
Code:
if(sourceType=='library') {
const Liboptions: CameraOptions = {
quality: 100,
destinationType: this.camera.DestinationType.FILE_URI,
encodingType: this.camera.EncodingType.JPEG,
mediaType: this.camera.MediaType.PICTURE,
sourceType:0,
saveToPhotoAlbum:true,
targetWidth:1024,
targetHeight:720,
allowEdit:true
}
this.camera.getPicture(Liboptions).then((imagePath) => {
// Special handling for Android library
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.');
});
} else {
const CamOptions: CameraOptions = {
quality: 100,
destinationType: this.camera.DestinationType.FILE_URI,
encodingType: this.camera.EncodingType.JPEG,
mediaType: this.camera.MediaType.PICTURE,
sourceType: this.camera.PictureSourceType.CAMERA,
targetWidth:1024,
targetHeight:720
}
//options.popoverOptions = CameraPopoverOption; options.correctOrientation = true;
this.camera.getPicture(CamOptions).then((imagePath) => {
// Special handling for Android library
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.');
});
}
you need to add this line in your config file in ios platform
<config-file parent="NSCameraUsageDescription" platform="ios" target="*-Info.plist">
<string>You can take photos</string>
</config-file>
Related
The photo I took using the application camera appears as a black screen. I looked at the other questions and tried some of the answers, but I can't translate the picture to base64. Could you help?
You can see the entire code from the link.
https://pastebin.ubuntu.com/p/4FwYdk5fvD/
takePicture(sourceType: PictureSourceType)
{
var options: CameraOptions = {
quality: 100,
sourceType: sourceType,
saveToPhotoAlbum: false,
correctOrientation: true
};
this.camera.getPicture(options).then(imagePath => {
if (this.plt.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());
}
});
}
i sorta had the same issue. I also wanted the name (not the path though), and i also wanted a base 64... so what i did what this:
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) => {
this.imgService.convertFilePathToBlob(imageData).subscribe(blob => {
this.image = blob;
});
let correctPath = imageData; // or subStr the parts you want
let currentName = this.image[1]; // grab the name
let currentImage = this.image[0]; // the image itself as base64
}).catch((err) => {
console.warn("takePicture Error: " + err);
});}
and the convert function... remember to import File, FileEntry from '#ionic-native/file/ngx'
convertFilePathToBlob(filePath:string) {
return from(this.file.resolveLocalFilesystemUrl(filePath)).pipe(
mergeMap((fileEntry: FileEntry) => {
return Observable.create(observer => {
fileEntry.file(file => {
const reader = new FileReader();
reader.onloadend = () => {
const imgBlob = new Blob([reader.result], { type: file.type });
observer.next([imgBlob, file.name]); // the name can be grabbed now
observer.complete();
};
reader.readAsArrayBuffer(file);
}, error => {
observer.error(error);
});
});
}));}
This works in my case, but i find it insane i had to do all this, and it took some debugging and googling... i hope it helps you in some way... :)
I am trying to display image taken from camera and displaying it to the view. I have searched for this answer on many websites but nothing worked. I have tried DomSanitizer, Base64 and even photo-library but the image returned from them is not displayed.
My home.ts file is
import { Component } from '#angular/core';
import { NavController } from 'ionic-angular';
import { Camera, CameraOptions } from '#ionic-native/camera';
import { DomSanitizer } from '#angular/platform-browser';
#Component({
selector: 'page-home',
templateUrl: 'home.html'
})
export class HomePage {
myPhoto:any;
image;
constructor(public navCtrl: NavController, private camera: Camera, public DomSanitizer: DomSanitizer) {
}
takePhoto(){
const options: CameraOptions = {
quality: 100,
targetHeight: 320,
targetWidth: 320,
destinationType: this.camera.DestinationType.FILE_URI,
sourceType: this.camera.PictureSourceType.CAMERA,
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 (DATA_URL):
this.myPhoto = 'data:image/jpeg;base64,' + imageData;
this.image = imageData;
console.log(this.myPhoto);
alert(this.myPhoto);
}, (err) => {
// Handle error
});
}
}
Here is my home.html code
<ion-header>
<ion-navbar>
<ion-title>
Ionic Blank
</ion-title>
</ion-navbar>
</ion-header>
<ion-content padding>
<button ion-button (click)="takePhoto()" >Take Photo</button>
<!-- <img src="{{myPhoto}}"/> -->
<!-- <img src="{{image}}"/> -->
<!-- <img [src]="DomSanitizer.bypassSecurityTrustUrl(myPhoto)"/> -->
<!-- <img data-ng-src="{{myPhoto}}"/> -->
<img src="data:image/jpeg;base64,file:///storage/sdcard0/Android/data/io.ionic.starter/cache/1533211220154.jpg"/>
</ion-content>
The commented code here is that i have tried but not succeeded.
I used the file plugin and its method readAsDataURL. It worked fine for me. Hope it'll helps people out there :)
const options: CameraOptions = {
quality: 100,
allowEdit: true,
sourceType: this.camera.PictureSourceType.CAMERA ,
saveToPhotoAlbum: true,
correctOrientation: true,
encodingType: this.camera.EncodingType.JPEG,
destinationType: this.camera.DestinationType.FILE_URI
}
this.camera.getPicture(options).then((imageData) => {
//imageData will hold the full file path so we need to extract filename and path using file plugin
var filename = imageData.substring(imageData.lastIndexOf('/')+1);
var path = imageData.substring(0,imageData.lastIndexOf('/')+1);
//then use it in the readAsDataURL method of cordova file plugin
//this.file is declared in constructor file :File
this.file.readAsDataURL(path, filename).then(res=>{
item.pic = res;
});
}, (err) => {
alert(err);
});
link for ionic cordova file plugin
Finally i got solution :
In component :
takePhoto(){
const options: CameraOptions = {
quality: 100,
targetHeight: 320,
targetWidth: 320,
destinationType: this.camera.DestinationType.FILE_URI,
sourceType: this.camera.PictureSourceType.CAMERA,
encodingType: this.camera.EncodingType.JPEG,
mediaType: this.camera.MediaType.PICTURE
}
this.camera.getPicture(options).then((imgFileUri) => {
this.myImg = (<any>window).Ionic.WebView.convertFileSrc(imgFileUri);
}, (err) => {
console.log(err);
});
}
In html :
<img [src]="myImg" />
Note :
cordova-plugin-ionic-webview >= 4
Use this function in your ts file
takePhoto(){
const options: CameraOptions = {
quality: 100,
targetHeight: 320,
targetWidth: 320,
destinationType: this.camera.DestinationType.DATA_URL,
sourceType: this.camera.PictureSourceType.CAMERA,
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 (DATA_URL):
this.myPhoto = 'data:image/jpeg;base64,' + imageData;
this.image = imageData;
console.log(this.myPhoto);
}, (err) => {
// Handle error
});
}
Use this in your html
<img [src]="myPhoto"/>
From new ionic and capacitor you can do it like this:
import { Capacitor } from '#capacitor/core';
Capacitor.convertFileSrc(filePath);
File Protocol​
Capacitor and Cordova apps are hosted on a local HTTP server and are served with the http:// protocol. Some plugins, however, attempt to access device files via the file:// protocol. To avoid difficulties between http:// and file://, paths to device files must be rewritten to use the local HTTP server. For example, file:///path/to/device/file must be rewritten as http://://path/to/device/file before being rendered in the app.
Modify your home.ts in following way,
private openGallery(): void {
let cameraOptions = {
sourceType: this.camera.PictureSourceType.PHOTOLIBRARY,
destinationType: this.camera.DestinationType.FILE_URI,
quality: 100,
targetWidth: 1000,
targetHeight: 1000,
encodingType: this.camera.EncodingType.JPEG,
correctOrientation: true
}
this.camera.getPicture(cameraOptions)
.then(file_uri => this.imageSrc = file_uri,
err => console.log(err));
}
In your html file,
<img [src]="imageSrc"/>
I am having a problem taking a picture and uploading it to an S3 bucket when using FILE_URI for the camera.DestinationType. When using this same process with the DATA_URL DestinationType it works fine.
When using FILE_URI the file that gets uploaded to the S3 bucket says it's corrupt. I did notice the file size is much smaller (~100B) than an actual image.
Here are the versions I am using:
Ionic Framework 3.9.2 and cordova-plugin-camera 4.0.2
Here is the code I'm using:
const options: CameraOptions = {
quality: 100,
correctOrientation: true,
destinationType: this.camera.DestinationType.FILE_URI,
encodingType: this.camera.EncodingType.JPEG,
mediaType: this.camera.MediaType.PICTURE,
sourceType: this.camera.PictureSourceType.CAMERA,
}
this.camera.getPicture(options).then((imageData) => {
console.log(imageData);
let base64data = 'data:image/jpeg;base64,' + imageData;
this.bigImg = base64data;
// imageData is either a base64 encoded string or a file URI
// If it's base64:
this.selectedPhoto = this.dataURItoBlob(this.bigImg);
}, (err) => {
// Handle error
console.log("Get Image Error: " + err);
});
this.sub = AWS.config.credentials.identityId;
let uploadMessage = "Uploading Image...";
let photoName = "testPic";
this.upload(this.selectedPhoto, uploadMessage, photoName)
.then(data => {
// Change active page to list
this.navCtrl.setRoot(TabsPage).then(() => {
});
});
dataURItoBlob(dataURI) {
// code adapted from: http://stackoverflow.com/questions/33486352/cant-upload-image-to-aws-s3-from-ionic-camera
let binary = atob(dataURI.split(',')[1]);
let array = [];
for (let i = 0; i < binary.length; i++) {
array.push(binary.charCodeAt(i));
}
return new Blob([new Uint8Array(array)], {type: 'image/jpeg'});
};
upload(selectedPhoto, uploadMessage, photoName) {
return new Promise((resolve, reject) => {
let loading = this.loadingCtrl.create({
content: uploadMessage
});
loading.present();
if (selectedPhoto) {
this.s3.upload({
'Key': 'protected/' + this.sub + '/' + photoName,
'Body': selectedPhoto,
'ContentType': 'image/jpeg'
}).promise().then((data) => {
this.data2 = data;
console.log('upload complete:', JSON.stringify(data));
loading.dismiss();
resolve(data);
}, err => {
console.log('upload failed....', JSON.stringify(err));
loading.dismiss();
reject(err);
});
} else {
loading.dismiss();
reject("upload failed");
}
});
I'm using ionic2: I want to upload an image from the gallery, crop it and send it to a server.
uploadImage(): Promise<any> {
var status = 'upload';
return new Promise(resolve =>
{
const options: CameraOptions = {
quality: 100,
sourceType: 2,
destinationType: this.camera.DestinationType.DATA_URL,
mediaType: this.camera.MediaType.PICTURE,
allowEdit: true
}
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;
console.log("imaaage ",this.base64Image);
resolve(this.base64Image);
}, (err) => {
console.log("error")
});
});
}
the problem is that: I want destinationType to be FILE_URL to send it, at the same time I want it to be DATA_URL to display it to the user.
what should I do to solve this problem?
I am trying to show images one after another at the same page taken from camera in ionic 2 but I am only able to show one images on the page.
Here is my code:
public base64Image: string;
public CompleteImage: Array<{image:string}>;
public OpenCamera() {
Camera.getPicture({
quality: 75,
destinationType: Camera.DestinationType.DATA_URL,
sourceType: Camera.PictureSourceType.CAMERA,
allowEdit: true,
encodingType: Camera.EncodingType.JPEG,
targetWidth: 200,
targetHeight: 200,
saveToPhotoAlbum: false
}).then(imageData => {
alert(1);
this.base64Image = "data:image/jpeg;base64," + imageData;
alert(2);
this.CompleteImage.push(this.base64Image);
alert(this.CompleteImage.length);
}, error => {
console.log("ERROR -> " + JSON.stringify(error));
});
}
for front end
if I am using this code
<ion-card *ngIf="base64Image">
<img [src]="base64Image" />
</ion-card>
then it is showing image but from collection. If I am trying to show it
<ion-card *ngFor="let i of CompleteImage">
<img [src]="i.image"/>
</ion-card>
then it is not working.
Here is the link from where I'm trying to achieve this. here
You should Ideally be using the ImagePicker API which can be obtained by importing ImagePicker from 'ionic-native' library.
import { Camera, ImagePicker } from 'ionic-native';
Have a function like this in a helper class (if you prefer)
export function pickImages() {
const options = {
quality: 50,
width: 1366,
height: 768,
maximumImagesCount: 10,
};
return ImagePicker.getPictures(options);
}
The above function will return a promise. You can use it like this.
pickImages().then((results) => {
for (var i = 0; i < results.length; i++) {
console.log('Image URI: ' + results[i]);
}
}, (err) => { });
Keep in mind this will return the location strings of images. You'll have to read this some other way
Reference
https://ionicframework.com/docs/v2/native/image-picker/