admin管理员组文章数量:1323682
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.
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.
- did you try this way ? src="{{lastImage}}" – Sarasa Gunawardhana Commented Apr 6, 2018 at 1:40
- No that does not seem to be working. – null Commented Apr 6, 2018 at 1:47
- Try this <img *ngIf="lastImage " [src]="lastImage" style="width: 100%"> – Manoj Bhardwaj Commented Apr 6, 2018 at 3:45
-
@ManojBhardwaj that does not work either. What happens is that img tag is not visible but when
lastImage
value changes then it does show img tag with width 100% however, the image that I took does not appear in that tag. – null Commented Apr 9, 2018 at 2:33 - Can you share the application that has the issue? – Keerthi Commented Apr 9, 2018 at 8:40
6 Answers
Reset to default 1He, 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)">
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));
});
}
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.
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
.
May this code helps you
App Component
export class AppComponent implements OnInit{
video: any;
canvas: any;
ngOnInit() {
this.startup();
}
startup(): void {
this.video = document.getElementById('video');
this.canvas = document.getElementById('canvas');
const nav = <any>navigator;
nav.getUserMedia = nav.getUserMedia || nav.mozGetUserMedia || nav.webkitGetUserMedia;
const self = this;
navigator.mediaDevices.getUserMedia({video: true, audio: false})
.then(function (stream) {
self.video.srcObject = stream;
self.video.play();
});
}
onBtnClicked(event: Event): void {
this.takePicture();
event.preventDefault();
}
takePicture() {
const context = this.canvas.getContext('2d');
context.drawImage(this.video, 0, 0, 100, 100);
}
}
And ponent's template is :
<div class="camera">
<video id="video" #video
width="width"
height="height"
(canplay)="onCanPlay($event)">
Video stream not available.
</video>
</div>
<canvas id="canvas" #canvas
width="width"
height="height">
</canvas>
<button (click)="takePicture()">Take Picture</button>
For detail check this
view template:
<img style="margin:5px; width: 100%" *ngIf="imageURL" src={{this.imageURL}} #myImage (click)="presentImage(myImage)" imageViewer/>
<button ion-button icon-left (click)="presentActionSheet()">
<ion-icon name="camera"></ion-icon>Select Image
</button>
TypeScript:
import { Camera,CameraOptions, CameraPopoverOptions } from '@ionic-native/camera';
import { ImageViewerController } from 'ionic-img-viewer';
then add 'Camera' in providers:
@Component({
//.....
providers: [Camera],
//....
})
then initialize the given objects:
_imageViewerCtrl: ImageViewerController;
imageURL;
camera: Camera;
then
options: CameraOptions = {
quality: 100,
destinationType: this.camera.DestinationType.DATA_URL,
encodingType: this.camera.EncodingType.JPEG,
mediaType: this.camera.MediaType.PICTURE
}
public presentActionSheet(){
this.camera.getPicture(this.options).then((imageData) => {
this.imageURL = 'data:image/jpeg;base64,' + imageData;
this.presentImage(this.imageURL);
}, (err) => {
console.log(err);
});
}
presentImage(myImage) {
const imageViewer = this._imageViewerCtrl.create(myImage);
imageViewer.present();
}
本文标签: javascriptDisplaying image taken from cameraStack Overflow
版权声明:本文标题:javascript - Displaying image taken from camera - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1742141967a2422619.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论