unable to display image from FILE URI, Ionic framework - ionic-framework

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"/>

Related

Ionic photo library does not load in iOS device

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>

how to save image base 64 as a file

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?

Cannot save image from base64 into gallery

import {CameraPreview, CameraPreviewOptions,} from '#ionic-native/camera-preview';
import {ToastController} from "ionic-angular";
import {Base64ToGallery} from '#ionic-native/base64-to-gallery';
private cameraPreviewOpts: CameraPreviewOptions = {
x: 0,
y: 0,
width: window.screen.width,
height: window.screen.height,
camera: 'rear',
tapPhoto: true,
previewDrag: true,
toBack: true,
alpha: 1
};
constructor(
public navCtrl: NavController,
public toastCtrl: ToastController,
public navParams: NavParams,
private camera: CameraPreview,
public platform: Platform,
private base64ToGallery: Base64ToGallery
)
{
var browser = this.platform.is('core');
if (!browser) {this.camera.startCamera(this.cameraPreviewOpts);}
}
takePicture() {
this.camera.takePicture({}).then((base64Data) => {
this.base64ToGallery.base64ToGallery(base64Data).then(
res => alert('Saved image to gallery ' + JSON.stringify(res)),
err => alert('Error saving image to gallery ' + JSON.stringify(err))
);
}, (err) => {
alert(JSON.stringify(err));
});
}
When I try to save save image in gallery then I have this error:
{"__zone_symbol__currentTask":{"type":"microTask","state":"notScheduled","source":"Promise.then","zone":"angular","cancelFn":null,"runCount":0}}
1) Install CameraPreview from npmjs cordova plugin add cordova-plugin-camera-preview
2) put this code before #Component declare let CameraPreview;
3) Don't forget to allow storage access and write storage in application params or with androidPermission
3) there is my code it's work !
takePic(){
const options = {
x: 0,
y: 0,
width: window.screen.width,
height: window.screen.height,
camera: CameraPreview.CAMERA_DIRECTION.FRONT, //or BACK
toBack: true,
tapPhoto: false,
tapFocus: false,
previewDrag: false,
disableExifHeaderStripping: true
};
CameraPreview.startCamera(options);
let base64option : Base64ToGalleryOptions = {
prefix: 'img',
mediaScanner: false
};
CameraPreview.takePicture({}, base64PictureData => {
let todecode = atob(base64PictureData);
this.base64ToGallery.base64ToGallery(btoa(todecode), base64option).then(
res => alert('Saved image to gallery '+ JSON.stringify(res)),
err => alert('Error saving image to gallery ' + JSON.stringify(err))
);
}, error =>{
alert(JSON.stringify(error));
});
}
You must start camera in background to take picture toBack: true, decode and encode your base64PictureData with atob & btoa
Your picture is now in internal storage/Pictures !
I think if you add
destinationType: 2
the image will save into locally and you will get a local path link.

image selection des not work in ionic 2 app

i am trying to open the photolibrary of android to select images using ionic 2.
here is the code of the home.ts in witch the camera plugin is used.
import { Component } from '#angular/core';
import { NavController } from 'ionic-angular';
import {Camera} from '#ionic-native/camera';
#Component({
selector: 'page-home',
templateUrl: 'home.html'
})
export class HomePage {
image640:any;
constructor(public navCtrl: NavController,public camera : Camera)
{
}
openGallery()
{
var options = {
quality: 100,
sourceType: this.camera.PictureSourceType.PHOTOLIBRARY,
saveToPhotoAlbum: true,
correctOrientation: true,
};
this.camera.getPicture(
options
).then(
(imageData)=>
{
this.image640 = 'data:image/jpeg;base64,'+imageData;
},
(err) =>
{
console.log(err);
}
);
}
}
And the code of the home.html is below :
<ion-header>
<ion-navbar>
<ion-title align="center">
Blank
</ion-title>
</ion-navbar>
</ion-header>
<ion-content padding>
<img src="image640" *ngIf="image640"/>
<Button align="center" ion-button (click)="openGallery()">Open
Gallery</Button>
</ion-content>
but when i click on the opengallery button, the android library is opened but when i select an image, a blank screen appear during about 8 seconds, and after that, the it is the rootpage that is displayed. Then i cannot see the selected image in my page.
can somebody help ?
Set options
var options = {
quality: 100,
sourceType: this.camera.PictureSourceType.PHOTOLIBRARY,
saveToPhotoAlbum: true,
correctOrientation: true,
};
Then select photos like this
this.camera.getPicture(options).then((imagePath) => {
// Special handling for Android library
if (this.platform.is('android') && sourceType ===
this.camera.PictureSourceType.PHOTOLIBRARY) { //when selecting from library
//your code goes here
} else { //when capturing by camera
//your code goes here
}

Show multiple image at one page taken from Camera with Ionic Native in Ionic 2

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/