How do you display a FILE_URI image taken by the user using #ionic-native/camera in Ionic 3?
I can use Ionic Native's Camera to get a FILE_URI image URL, with a result like this:
file:///var/mobile/Containers/Data/Application/XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXX/tmp/cdv_photo_005.jpg
However, When I try to display this image back to the user by referring to the URI in my view template, the image never loads.
Things I've tried:
-Using the image URI directly in the view
<img src="{{profile.image}}"> // Never loads
-Sanitizing the URI by including DomSanitizer in the page component:
<img [src]="domSanitizer.bypassSecurityTrustUrl(profile.image)"> // Never loads
I would rather not use a base64 image because of the performance drag. What am I doing wrong here?
import { normalizeURL } from 'ionic-angular'; ionic3 <img> tag src
<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);
// Alternatively if the problem only occurs in ios and normalizeURL
// doesn't 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));
});
}
Hi try to use File Path ionic plugin
path = "file:///var/mobile/Containers/Data/Application/XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXX/tmp/cdv_photo_005.jpg";
this.filePath.resolveNativePath(path)
.then(filePath => console.log(filePath))
.catch(err => console.log(err));
Please read the documentation
https://ionicframework.com/docs/native/file-path/
You can use the below code for display the image
savePhotoClick = () =>{
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 (DATA_URL):
this.base64Image = 'data:image/jpeg;base64,' + imageData;
}, (err) => {
// Handle error
});
Then use the img tag for display
<img [src]="base64Image" *ngIf="base64Image" />
Related
Steps :
Click on camera button in app then camera open
take picture front/back picture dsiplay
selection option cancel or ok then I have click ok
app restart (means app open from start page with splase screen)
Notes :
My android version 11 [I am testing this code in android 11(MI device) and android 10(Motorola) devices]
All the permissions of camera access is 100% set.
The issue doesn't come in Android 10.
The issues comes in just Android 11.
This is my Code snippet
const options: CameraOptions = {
quality: 100,
destinationType: this.camera.DestinationType.FILE_URI,
encodingType: this.camera.EncodingType.JPEG,
mediaType: this.camera.MediaType.PICTURE
}
this.camera.getPicture(options).then((imageData) => {
console.log("imageData ===> ",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;
}, (err) => {
console.log("errr",err);
this.utilServices.openForSuccessError({ value: false, message1: err});
// Handle error
});
I have an app that allows a user to select a photo from the gallery or take a photo via camera. I am trying to display an image that was taken via camera and it works fine, it returns a file path like
file:///Users/ray/Library/Developer/CoreSimulator/Devices/C8202B3B-300B-4819-8CD3-4C4AA690CE7C/ data/Applications/D82BF64E-6DD1-4645-B637-BCF65001FD29/tmp/cdv_photo_003.jpg
but when I try to select a photo from a gallery it shows a broken image thumbnail, and it turns a file path like.
content://com.android.providers.media.documents/document/image%3A21
Ionic CLI Version: PRO 4.2.1
Cordova Verion: 8.0.0
NPM Version: 6.4.1
Node.js version: 8.11.3
Platform: Android
I've also tried searching for a solution but it didn't work or I am still doing something wrong
Unable to load image when selected from the gallery on Android in phonegap
https://www.raymondcamden.com/2014/10/10/Cordova-the-Camera-plugin-AngularJS-and-Ninja-Cats
ionic cordova : how to display an image in img tag from android gallery when i get content:// url from filechooser plugin
Unable to load image when selected from the gallery on Android 4.4 (KitKat) using PhoneGap Camera Plugin
Some of them suggests using this code
if (imageURI.substring(0,21)=="content://com.android") {
photo_split=imageURI.split("%3A");
imageURI="content://media/external/images/media/"+photo_split[1];
}
but this solution is not that robust cause not all of the image sources returns the same file path that contains 'content://com.android' like the photos that came from Google Photos which returns 'content://com.google.android'
_Some of them also suggests using DATA_URL on destination type but it is memory intensive and may cause the app to crash_
Here is my code:
TS file
selectImage(sourceType) {
const options: CameraOptions = {
quality: 100,
destinationType: this.camera.DestinationType.FILE_URI,
encodingType: this.camera.EncodingType.JPEG,
mediaType: this.camera.MediaType.PICTURE,
saveToPhotoAlbum: true,
sourceType: sourceType
}
this.camera.getPicture(options).then((imageData) => {
let base64Image = 'data:image/jpeg;base64,' + imageData;
this.imagePreview = imageData;
}, (err) => {
this.toastCtrl.presentToast(err);
});
}
HTML File
<img src="{{imagePreview}}" />;
I hope someone could help me with this. Thank you in advance 💖.
ts:
public base64Image:string;
public getImage(){
const options: CameraOptions = {
quality: 100,
destinationType: this.camera.DestinationType.DATA_URL,
encodingType: this.camera.EncodingType.JPEG,
mediaType: this.camera.MediaType.PICTURE
}
this.camera.getPicture(options).then((imageData) => {
this.base64Image = 'data:image/jpeg;base64,' + imageData;
}, (err) => {
// Handle error
});
}
html:
<imge src={{base64Image}} />
Give this a try:-
//From Gallery
ChooseGallery() {
var _self=this;
const options: CameraOptions = {
allowEdit: true,
correctOrientation: true,
quality: 100, // picture quality
destinationType: this.camera.DestinationType.FILE_URI,
encodingType: this.camera.EncodingType.JPEG,
sourceType: this.camera.PictureSourceType.SAVEDPHOTOALBUM
}
this.camera.getPicture(options).then((ImageData) => {
_self.base64value = ImageData;
})
}
From Camera
ChooseCamera() {
var _self=this;
const options: CameraOptions = {
allowEdit: true,
correctOrientation: true,
quality: 100, // picture quality
destinationType: this.camera.DestinationType.FILE_URI,
encodingType: this.camera.EncodingType.JPEG,
mediaType: this.camera.MediaType.PICTURE
}
this.camera.getPicture(options).then((ImageData) => {
_self.base64value = ImageData;
})
}
I hope this helps! Thanks!
Solved my problem using DomSanitizer https://devfanaticblog.com/working-with-camera-in-ionic-2-and-ionic-native/
let options: CameraOptions = {
quality: 100,
sourceType: this.camera.PictureSourceType.SAVEDPHOTOALBUM,
saveToPhotoAlbum: true,
correctOrientation: true,
encodingType: this.camera.EncodingType.JPEG,
destinationType: this.camera.DestinationType.FILE_URI
};
this.camera.getPicture(options).then((imageData) => {
let photo_split=imageData.split("%3A");
let photo_split2=photo_split[0].split("?");
let filename = photo_split2[0].substring(photo_split2[0].lastIndexOf('/')+1);
let path = photo_split2[0].substring(0,photo_split2[0].lastIndexOf('/')+1);
alert(photo_split2[0])
alert(filename)
alert(path)
this.file.readAsDataURL(path, filename).then(res=> {
alert("FUNCIONA!")
this.imageURI = res;
}).catch((reason) => {
alert(JSON.stringify(reason));
});
}).catch((reason) => {
alert(JSON.stringify(reason));
});
//HTML
<img alt="uploaded Image" [src]="imageURI">
My backen looks like this. The backend required a file and 2 string params
#multipart/form-data
file: File,
title: string,
content: string
I used to use to select file then upload it to server via httpClient and formData
const formData = new FormData();
formData.append('title', form.value.title);
formData.append('content', form.value.description);
formData.append('file', this.img);
this.http.post(this.apiUrl + '/img', formData, settings);
Everything works just fine.
But now I decide that I do not want to use any more. I decide to use native camera
getPictureFromCamera() {
return new Promise((resolve, reject) => {
const options: CameraOptions = {
quality: 100,
destinationType: this.camera.DestinationType.FILE_URI,
encodingType: this.camera.EncodingType.JPEG,
mediaType: this.camera.MediaType.PICTURE
}
this.camera.getPicture(options).then((imageData) => {
let base64Image = null;
//get photo from the camera based on platform type
base64Image = normalizeURL(imageData);
resolve(base64Image);
}, (error) => {
console.debug("Unable to obtain picture: " + error, "app");
reject(error);
});
})
}
I successfully can take and display the picture. The problem is that my function only return the path of image (not the file). How can I get the actual file so I can use form-data and httpClient to post it to my server.
I want to use my old formdata function so I just need a file. Is there any way I just only get a file from imgPath.
Note: when I log 'base64Image' (you can see in the code above)
http://localhost:8080/var/mobile/Containers/Data/Application/85D7DD14-849C-4ADE-9005-D8165CC2A55B/tmp/cdv_photo_001.jpg
I am using IONIC 3.7.0 in my current project. In one requirement I need to use cordova camera plugin to take photo uri from image gallery. Every time when I am trying to get the URI , I get the data_uri which is base64 long string.
I only need the file_uri of image to go further. Please suggest.
var options = {
sourceType: Camera.PictureSourceType.PHOTOLIBRARY,
destinationType: Camera.DestinationType.FILE_URI
};
Camera.getPicture(options)
.then((imageData) => {
console.log(imageData);
this.fileToUpload = imageData;
const base64Image = "data:image/jpeg;base64," + imageData;
this.preloadImage._img.src = base64Image;
this.codeservice.doProfileImageUpload(base64Image)
.subscribe(res => {
if(res.length()>0){
console.log('updated');
}
})
}, (err) => {
console.log(err);
});
I am trying to invoke the camera and get the path of the taken picture to send it to my FTP.
I am getting error when I use chrome://inspect like
GET data:image/png;base64,file:///storage/sdcard0/Android/data/com.ionicframework.camera108827/cache/1462163674353.png net::ERR_INVALID_URL
I have successfully invoked the camera and taken the picture but I am getting the broken image.
here is my code fore getting the image path of my taken picture.
.controller('mycontroller',function($scope,$cordovaCamera){
$scope.takePicture = function(){
var options = {
quality : 75,
destinationType: Camera.DestinationType.FILE_URI,
sourceType: Camera.PictureSourceType.CAMERA,
allowEdit : false,
encodingType: Camera.EncodingType.PNG,
targetWidth: 250,
targetHeight: 250,
popoverOptions: CameraPopoverOptions,
saveToPhotoAlbum: false
};
$cordovaCamera.getPicture(options).then(function(imageURI) {
//$scope.image = "data:image/jpeg;base64," + imageData;
console.log('invokeing cordovaCamera');
$scope.image = "data:image/png;base64," + imageURI;
console.log($scope.image);
console.log(imageURI);
//$scope.apply();
}, function(err) {
// An error occured. Show a message to the user
});
};
});
in my index.html
<ion-content ng-controller="mycontroller">
<img ng-show="image !== undefined" ng-src="{{image}}">
<img ng-show="image === undefined" ng-src="http://placehold.it/250x250">
<button class="button" ng-click="takePicture()">Take Picture</button>
</ion-content>
The problem is on the this line
$scope.image = "data:image/png;base64," + imageURI;
It should be like this
$scope.image = imageURI;