I am trying to use camera plugin with cordova app in ionic angular.js. My problem is that when i get picture it gives me a url of image not base64 string
I need base64 string.
in Services.js
.factory('Camera', function($q) {
return {
getPicture: function(options) {
var q = $q.defer();
navigator.camera.getPicture(function(result) {
q.resolve(result);
}, function(err) {
q.reject(err);
}, options);
return q.promise;
}
}
});
I user code above this returns
file:///storage/emulated/0/Android/data/com.example.app/cache/1313513121.jpg
but I want base64 string because I send it to server to save the image in server
in Controller.js
$scope.AddImage = function () {
var options = {
quality : 75,
targetWidth: 200,
targetHeight: 200,
sourceType: 1
};
Camera.getPicture(options).then(function(imageData) {
alert(imageData);
var item={
image: imageData
}
Pictures.push(item);
$scope.Photos = Pictures;
}, function(err) {
console.log(err);
});
}
I wrote code above. How can I solve this problem
Thanks in advance
Use the destinationType option parameter with value DATA_URL on the [ cameraOptions ].
navigator.camera.getPicture( cameraSuccess, cameraError, [
cameraOptions ] );
The option destinationType: Camera.DestinationType.DATA_URL will allow you to take a photo and retrieve the Base64-encoded image. Default this is set to destinationType: Camera.DestinationType.FILE_URI which will retrieve the image file location.
Below a general code sample which you can use to adapt your existing code.
navigator.camera.getPicture(onSuccess, onFail, { quality: 50,
destinationType: Camera.DestinationType.DATA_URL
});
function onSuccess(imageData) {
var image = document.getElementById('myImage');
image.src = "data:image/jpeg;base64," + imageData;
}
function onFail(message) {
alert('Failed because: ' + message);
}
Documentation here
Related
I have little knowledge on promises ,
What i have been doing is to convert html to pdf , thankfully html2pdf works great ,
Now where I was stuck is getting the pdf as a file and post to server with form-data
I have somehow found to get pdf encoded string from here
But it is a promise and i have a function as :
genPDF:function(){
var element = document.getElementById('canvasId');
var opt = {
filename: 'nobutton.pdf',
image: { type: 'jpeg', quality: 0.98 },
// html2canvas: { scale: 2 },
};
html2pdf().from(element).set(opt).toPdf().output('datauristring').then(function (res) {
var blobString = res;
console.log(blobString);
});
}
But here it doesn't log at first time , but then the function is called again and then logs , why is that ?? could i get it for the first time the function called ?
Can some one help me how to get the pdf from html2pdf as a file so that can append it to form-data , any help is really appreciated , Thanks :)
#Sophie - here is the asnyc version as discussed in the comments.
async genPDF() {
var element = document.getElementById('canvasId');
var opt = {
filename: 'nobutton.pdf',
image: { type: 'jpeg', quality: 0.98 },
// html2canvas: { scale: 2 },
};
let blobString = await html2pdf().from(element).set(opt).toPdf().output('datauristring');
console.log(blobString);
}
When I take a picture everything works fine. The pic is made and I see it afterwards on the page. When I click to retake the pic I can do it, but now come the problem. The old picture is placed under the first picture Ive taken. I know that bc I can see a little bit of my 2. picture laying under my first picture. To see my second picture I have take a 3. picture (second time retake picture) Now the first pic is deleted, the 2. pic is on the top and the 3. is placed under the 2. pic. How can I achieve that the pic is directly deleted when I retake a picture?
export class PostPage {
public photos: any;
public base64Image: string;
constructor(public navCtrl: NavController, private camera: Camera) {
}
ngOnInit(){
this.photos = [];
}
ionViewDidEnter(){ //Damit Kamera automatisch öffent
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) => {
// imageData is either a base64 encoded string or a file URI
// If it's base64:
this.base64Image = 'data:image/jpeg;base64,' + imageData;
this.photos.push(this.base64Image);
this.photos.reverse();
}, (err) => {
// Handle error
});
}
cancel(){
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) => {
// imageData is either a base64 encoded string or a file URI
// If it's base64:
this.base64Image = 'data:image/jpeg;base64,' + imageData;
this.photos.push(this.base64Image);
this.photos.reverse();
}, (err) => {
// Handle error
});
}
}
I am developing a mobile application and I getting an error when the user try to change the picture profile, the error after do a lot of debugging is not in the camera is in the file transfer function when I try to send the image to the server, there is no error code or message, simply the application stop work, this is the code:
$scope.addImage = function (option) {
var options = {
quality: 75,
targetWidth: 300,
destinationType: Camera.DestinationType.DATA_URL,
targetHeight: 300,
saveToPhotoAlbum: false,
correctOrientation: true
};
if (option == 1) {
options.sourceType = Camera.PictureSourceType.CAMERA;
} else {
options.sourceType = Camera.PictureSourceType.PHOTOLIBRARY;
}
$cordovaCamera.getPicture(options).then(function (imageData) {
console.log("IMAGE DATA");
console.log(imageData);
//alert("SUCCESS");
$scope.user.image = "data:image/jpeg;base64," + imageData;
console.log(JSON.stringify($scope.user));
$scope.savePicture();
}, function (err) {
alert("ERRROR");
alert(JSON.stringify(err));
// An error occured. Show a message to the user
});
};
$scope.savePicture = function () {
var options = {
fileKey: "avatar",
fileName: "image.jpg",
chunkedMode: false,
mimeType: "image/jpeg",
headers: {
Authorization: "Bearer " + $auth.getToken()
}
};
$cordovaFileTransfer.upload(api.getApi()+"user/updatephoto", $scope.user.image, options).then(function (result) {
console.log("SUCCESS: " + JSON.stringify(result.response));
}, function (err) {
console.log("ERROR: " + JSON.stringify(err));
alert("ERROR: " + JSON.stringify(err));
}, function (progress) {
// constant progress updates
});
};
Thank in advice for your help
you are not calling return appropriately on your functions that return a promise. From a quick review, $scope.savePicture(); should be return $scope.savePicture();
and $cordovaFileTransfer.upload() should also be return $cordovaFileTransfer.upload()
I would start there and see if you start to make some progress.
I had to debug the entire application including the cat log of android and I found the problem.
The problem was that I am using Ionic with crosswalk and the version of FileTransfer that I was using does not support crosswalk.
I fix this problem just installing the last version of file transfer:
cordova-plugin-file-transfer 1.2.1 "File Transfer"
Good day, i have a project on cordova that uses image gallery and camera and stores images in local cache folder.
So i installed:
org.apache.cordova.camera 0.3.1 "Camera"
org.apache.cordova.file 1.3.1 "File"
org.apache.cordova.file-transfer 0.4.6 "File Transfer"
Android and iOS works perfectly, but when it comes to WP8 (Windows Phone 8), following code:
$scope.uploadImageFromPhone = function(isCamera){
console.log('uploadImageFromPhone');
var opt = {
quality: 50,
destinationType: Camera.DestinationType.FILE_URI,
sourceType: (isCamera) ? Camera.PictureSourceType.CAMERA : Camera.PictureSourceType.PHOTOLIBRARY,
encodingType: Camera.EncodingType.JPEG
};
function onGetImageSuccess(fileUrl) {
console.log('onGetImageSuccess:\n'+fileUrl);
window.resolveLocalFileSystemURL(fileUrl, resolveSuccess, resolveFails);
}
function onGetImageFail(message) {
//console.log('onGetImageFailed:\n' + JSON.stringify(message));
}
function resolveSuccess (path) {
console.log('resolveSuccess:');
console.log(JSON.stringify(path));
uri = path.nativeURL;
//wp8 returns null as path.nativeURL
/*IE10 specific hack*/
if (navigator.userAgent.match(/IEMobile\/10\.0/)) {
uri = path.fullPath;
}
}
function resolveFails(err){
console.log('resolveFails:\n' + JSON.stringify(err));
};
navigator.camera.getPicture(onGetImageSuccess, onGetImageFail, opt);
}
The resolveSuccess function always returns path variable as shown below:
{"isFile":true,"isDirectory":false,"name":"wp_ss_20140923_0001.png","fullPath":"///CapturedImagesCache/wp_ss_20140923_0001.png","filesystem":"<FileSystem: temporary>","nativeURL":null}
Problem is that nativeURL is null.
According to my app, chosen file must be put in application local cache, so i try to download it and store in cache by approaching to fullPath with file-transfer plugin:
var fileTransfer = new FileTransfer();
fileTransfer.download(
uri, // equals to '///CapturedImagesCache/wp_ss_20140923_0001.png'
'wp_ss_20140923_0001.png',
function(entry){
//file processing
console.log('downloaded successfull');
},
function(error){
console.log("download error" + JSON.stringify(error));
},
false,
{}
);
This code always returns me console output:
download error: {"code":2,"source":"///CapturedImagesCache/wp_ss_20140923_0001.png","target":null,"http_status":null,"body":null,"exception":null}
I don't get it, what am i doing wrong here?
P.S: cordova version: '3.6.3-0.2.13'
This is probably simple and covered by some combination of functions in PhoneGap's "Camera" plugin, "File" plugin, or "File-Transfer" plugin. I understand the user can select a file with:
navigator.camera.getPicture(function (fileURI) {
// *** need help here ***
}, function ()
// handle errors
}, {
destinationType: window.Camera.DestinationType.FILE_URI,
sourceType: window.Camera.PictureSourceType.PHOTOLIBRARY,
mediaType: window.Camera.MediaType.ALLMEDIA
});
I can also change to destinationType: window.Camera.DestinationType.DATA_URL if that makes a difference.
My goal in the success handler is to get a File object (https://developer.mozilla.org/en-US/docs/Web/API/File).
Something like this should do it.
navigator.camera.getPicture(function (fileURI) {
window.resolveLocalFileSystemURL(fileURI,
function(fileEntry){
alert("got image file entry: " + fileEntry.fullPath);
// fileEntry.file() should return a raw HTML File Object
},
function(){//error}
);
}, function (){
// handle errors
}, {
destinationType: window.Camera.DestinationType.FILE_URI,
sourceType: window.Camera.PictureSourceType.PHOTOLIBRARY,
mediaType: window.Camera.MediaType.ALLMEDIA
});
window.resolveLocalFileSystemURI(fileURI, function(fileEntry) { /* your code here */ });