Need little help on cordovaSocialShare plugin
I'm trying to share an image via Whatsapp which was selected in my ionic app but i'm not able to share the image
<form name = myForm controller="ExampleController" ng-
submit="ShareAnywhere(myForm)">
<div class="myDivClass">
<input type="file" ng-model="share.shareImage">
<button ng-click="Submitted=true">Share</button>
</div>
<form>
and below goes my controller
app.controller('ExampleController',function($scope, $cordovaSocialSharing, $filter){
$scope.shareAnywhere=function(myForm){
var eDate = new Date();
var message = "Hi! this is an wahtsapp msg";
var image = this.share.shareImage;
var link = 'http://myAwsomeWebsite.com';
var subject = 'My Subject';
$cordovaSocialSharing.share(message, subject, image, link);
}
});
I'm able to share the text but it wouldn't add image with it
I might be doing it completely wrong please let me know what is the correct way to do it thanks in advance
For capturing the image on click of button added at HTML file:
takePicture(){
Camera.getPicture({
destinationType: Camera.DestinationType.DATA_URL,
targetWidth: 1000,
targetHeight: 1000
}).then((imageData) => {
// imageData is a base64 encoded string
this.base64Image = "data:image/jpeg;base64," + imageData;
}, (err) => {
console.log(err);
});
}
sharePicture(){
// Share via whatsapp
this.socialSharing.shareViaWhatsApp(this.message,this.base64Image,this.url).then(() => {
// Success!
}).catch(() => {
// Error!
});
}
Just declare the message, image and url as string.
the parameter image should be a path(URL) to the Image. and not the Image data.
Related
I have been struggling for a few days with taking a photo with the phone camera, using Ionic and Android device, and sending it to the server in a post request. Optionally, I want to display the image to the screen.
I read a lot of previous posts with similar problems, but none of the solutions worked for me. I want to mention that I am quite new to the ionic world, so I am still learning. Maybe it is a stupid problem that I cannot see.
Before adding the code that I tried, I want to list the things that I have tried so far:
Used FILE_URL and DATA_URL for the destinationType option
Manually convert the image to base 64
Used domSanitizer.bypassSecurityTrustUrl(b64img) in the .html file
Please, see below the code that I tried:
This is the code for taking the photo:
const options: CameraOptions = { // photo options
quality: 50,
destinationType: this.camera.DestinationType.DATA_URL,
encodingType: this.camera.EncodingType.JPEG,
mediaType: this.camera.MediaType.PICTURE,
} // take picture
this.camera.getPicture(options).then((imageData) => {
this.imageData = imageData;
this.image = ( < any > window).Ionic.WebView.convertFileSrc(imageData);
//extra http://localhost/file.. and I slice it to remove extra chars
this.image = this.image.slice(27);
},
(err) => {
this.helperService.showAlert(JSON.stringify(err));
});
This is the code for uploading the photo to the server:
upload() { // upload method
let url = 'url/to/post';
const date = new Date().valueOf();
const imageName = date + '.jpeg';
console.log(this.imageData);
-- - > undefined
//slice it to remove extra chars
this.imageData = this.imageData.slice(27);
const imageBlob = this.dataURItoBlob(this.imageData);
const imageFile = new File([imageBlob], imageName, {
type: 'image/jpeg'
});
let postData = new FormData();
postData.append('file', imageFile);
let data: Observable < any > = this.httpClient.post(url, postData);
data.subscribe((result) => {
this.helperService.showSuccess(result);
});
}
And this is the blob function:
dataURItoBlob(dataURI) {
const byteString = window.atob(dataURI);
const arrayBuffer = new ArrayBuffer(byteString.length);
const int8Array = new Uint8Array(arrayBuffer);
for (let i = 0; i < byteString.length; i++) {
int8Array[i] = byteString.charCodeAt(i);
}
const blob = new Blob([int8Array], {
type: 'image/jpeg'
});
return blob;
}
This is my HTML file:
<ion-content>
<ion-grid>
<img [src]="DomSanitizer.bypassSecurityTrustUrl(image)">
</ion-grid>
<ion-button (click)="upload()" color="success">
<ion-icon slot="icon-only" name="checkmark"></ion-icon>
</ion-button>
</ion-content>
Problems:
The photo is not displayed on the screen and my image is Undefined - I tried both with and without DomSanitizer
this.imageData is undefined inside the upload() method
This is the reference post that I followed, but I cannot manage to see the problems:
Capture and upload image to server using Ionic 4
Looking at this reference post, I sliced even the extra characters displayed in front of the image, but I did not manage to solve the problems.
Let me know if I should add any other information. Thank you for your help!
I manage to display the image on the screen by using:
let b64 = 'data:image/jpeg;base64,' + imageData;
this.image = b64;
instead of
this.image = (<any>window).Ionic.WebView.convertFileSrc(imageData);
Unfortunately, this.imageData is still undefined, and I cannot figure out why.
Update: Looks like the photo is sent to bakend now, but its size is 0 and backend (which is Nodejs) cannot use it. What should I do? Should I parse it in some way?
Thank you!
I am trying to develop an android application using react-native. and one of the requirement is to automatically save the capture image based on pre-defined filename programmatically. I am using react-native-image-picker.
The API of image-picker does not show way to save the image with per-defined filename programmatically. The tutorial I am using, does not show either.
Thanks a lot.
I have done it like this. This may help you out.
ImagePicker.launchCamera({},(responce)=>{
this.setState({
pickedImage: { uri: res.uri }
});
console.log(this.state.serverTime);
const file ={
uri : responce.uri,
//give the name that you wish to give
name :this.state.currentTimeInMilisec+'.jpg',
method: 'POST',
path : responce.path,
type : responce.type,
notification: {
enabled: true
}
}
console.log(file);
})
}
I have done as below. It is working fine.
ImagePicker.launchCamera({},(responce)=>{
const localTime = new Date().getTime();
const file ={
uri : responce.uri,
//give the name that you wish to give
name :localTime +'.jpg',
method: 'POST',
path : responce.path,
type : responce.type,
notification: {
enabled: true
}
}
console.log(file);
})
}
I have created one sample app using telerik app builder. I have created one simple view and one js file, render one image in view and convert it into base-64. I have requirement to download this image and save it to device internal storage using javascript
I have used download.js plugin of javascript but download functionality is not working.Please give suggestion.
My Code is below:
function (image)
{
var imageData = image.src;
imageData = imageData.replace('data:image/png;base64,', '');
download(imageData, "image11111", "image/png");
}
I found my own question's answer.
You can download image in mobile device using cordova filetransfer.
function download()
{
var filepath = encodeURI("http://www.telerik.com/sfimages/default-source/logos/app_builder.png"),
window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, function (fileSystem) {
fileSystem.root.getFile("sample.jpg", { create: true, exclusive: false }, function (fileEntry) {
// get the full path to the newly created file on the device
var localPath = fileEntry.fullPath;
// massage the path for android devices (not tested)
if (device.platform === "Android" && localPath.indexOf("file://") === 0) {
localPath = localPath.substring(7);
}
// download the remote file and save it
var remoteFile = filepath;
//loadingOverlay.displayLoading("Image will be save on your device.");
var fileTransfer = new FileTransfer();
fileTransfer.download(remoteFile, localPath, function (newFileEntry) {
// successful download, continue to the next image
var dwnldImagePath = newFileEntry.fullPath;
console.log('successful download');
},
function (error) { // error callback for #download
console.log('Error with #download method.', error);
});
});
function(error) { // error callback for #getFile
console.log('Error with #getFile method.', error);
});
})
}
Can anyone shed any light on why, using the Image Factory module to download and store images on Android, does it ignore the transparency on PNG graphics and give them a black background?
It works fine on iOS and everything is "as is".
Do I need to add anything to the download script to retain the transparency?
Help!
Here is my download script, I'm building using Titanium 3.5.1 GA:
function getMarker(url, filename) {
// this will enable us to have multiple file sizes per device
var filename2 = filename.replace(".png", "#2x.png");
var filename3 = filename.replace(".png", "#3x.png");
var mapMarker = Ti.Filesystem.getFile(Ti.Filesystem.applicationDataDirectory, 'map_marker_icons', filename);
var mapMarker2 = Ti.Filesystem.getFile(Ti.Filesystem.applicationDataDirectory, 'map_marker_icons', filename2);
var mapMarker3 = Ti.Filesystem.getFile(Ti.Filesystem.applicationDataDirectory, 'map_marker_icons', filename3);
// now we need to download the map marker and save it into our device
var getMarker = Titanium.Network.createHTTPClient({
timeout: 30000
});
getMarker.onload = function() {
// if the file loads, then write to the filesystem
if (getMarker.status == 200) {
// resize the images into non-retina, retina and retina HD and only download and resize what is actyally required
var getOriginal = ImageFactory.imageWithAlpha(this.responseData, {});
var resized2 = ImageFactory.imageAsResized(getOriginal, {
width: 50,
height: 50
});
mapMarker.write(resized2);
Ti.API.info(filename + " Image resized");
//I ALWAYS NULL ANY PROXIES CREATED SO THAT IT CAN BE RELEASED
mapMarker = null;
} else {
Ti.API.info("Image not loaded");
}
// load the tours in next
loadNav();
};
getMarker.onerror = function(e) {
Ti.API.info('XHR Error ' + e.error);
//alert('markers data error');
};
getMarker.ondatastream = function(e) {
//Ti.API.info('Download progress: ' + e.progress);
};
// open the client
getMarker.open('GET', url);
// change the loading message
MainActInd.message = 'Downloading Markers';
// show the indicator
MainActInd.show();
// send the data
getMarker.send(); }
Any help would be much appreciated!
Simon
Please try the following code, I tried it on Android and iOS with a png Url, first I GET the photo with HTTP client request, then I save it as a file with extension png and then I read it with an ImageView.
index.js:
$.win.open();
savePng("https://cdn1.iconfinder.com/data/icons/social-media-set/29/Soundcloud-128.png");
function savePng(pngUrl) {
var client = Titanium.Network.createHTTPClient({
onload : function(e) {
var image_file = Ti.Filesystem.getFile(Titanium.Filesystem.applicationDataDirectory, "test.png");
image_file.write(this.responseData);
$.img.image = image_file.read();
},
onerror : function(e) {
alert(e.error);
},
timeout : 10000
});
client.open("GET", pngUrl);
client.send();
}
index.xml:
<Alloy>
<Window id="win" backgroundColor="gray">
<ImageView id="img" />
</Window>
</Alloy>
I am using following code to get image base64 data to display and upload to server.
But i want to save this captured image in sdcard folder. Please help me to do this.
This is necessary for me to get base64 image data because server support only this format. That's why i am using destinationType = 0 (means DATA_URL). I have base64 image data now but how can i save this data to sdcard?
uploadPhoto(isSourceCamera, onPhotoDataSuccess, onFail);
function uploadPhoto(isSourceCamera, onPhotoDataSuccess, onFail)
{
pictureSource = navigator.camera.PictureSourceType;
if (isSourceCamera)
{
//QUALITY MUST BE LOW TO AVOID MEMORY ISSUES ON IPHONE4 ! (and other low memory phones).
//must resize to make it faster to upload and avoid failure with low memory phones.
navigator.camera.getPicture(onSuccessFunc, onFail, {
quality : 35,
sourceType : pictureSource.CAMERA,
targetWidth:750,
targetHeight:750,
allowEdit:true,
destinationType:0
});
}
else
{
navigator.camera.getPicture(onSuccessFunc, onFail, {
quality : 35,
sourceType : pictureSource.PHOTOLIBRARY,
targetWidth:750,
targetHeight:750,
allowEdit:true,
destinationType:0
});
}
}
function onPhotoDataSuccess(imageData)
{
**//I want to smae my image here in sdcard folder.**
var nodeid = localStorage.getItem("user_nodeid");
var modifyImgData = imageData.replace(' ', '+');
document.getElementById('image').src = setLocalStorageImage(localStorage.getItem(nodeid+"image"), modifyImgData);
document.getElementById('profileMenu').src = setLocalStorageImage(localStorage.getItem(nodeid+"smallimage"), modifyImgData);
$.ajax({
type: "POST",
url: appURL+"api/upload/image/" +nodeid+ "/1",
data: "image=" + encodeURIComponent(modifyImgData),
success: function(msg){
//No need to do anything here
if (msg.documentElement.getElementsByTagName("message")[0].childNodes[0].nodeValue != 'success')
onFail('Error in uploading image at server. Please try again.');
}
});
}
function onFail(message){
alert(message);
}
Here is the correct answer to the original question:
How to move captured image in PhoneGap to a folder in sdcard?
function onfail(error,caller){
error = error || '[error]';
caller = caller || '[caller]';
alert('Error > '+caller+" code: "+error.code);
};
/*
Error codes
NOT_FOUND_ERR = 1;
SECURITY_ERR = 2;
ABORT_ERR = 3;
NOT_READABLE_ERR = 4;
ENCODING_ERR = 5;
NO_MODIFICATION_ALLOWED_ERR = 6;
INVALID_STATE_ERR = 7;
SYNTAX_ERR = 8;
INVALID_MODIFICATION_ERR = 9;
QUOTA_EXCEEDED_ERR = 10;
TYPE_MISMATCH_ERR = 11;
PATH_EXISTS_ERR = 12;
*/
function doCameraAPI() {
// Retrieve image file location from specified source
navigator.camera.getPicture(getImageURI, function(message) {
alert('Image Capture Failed');
}, {
quality : 40,
destinationType : Camera.DestinationType.FILE_URI
});
}; //doCameraAPI
function getImageURI(imageURI) {
//resolve file system for image to move.
window.resolveLocalFileSystemURI(imageURI, gotFileEntry, function(error){onfail(error,'Get Target Image')});
function gotFileEntry(targetImg) {
//alert("got image file entry: " + targetImg.name);
//now lets resolve the location of the destination folder
window.resolveLocalFileSystemURI(POSTPATH, gotDestinationEntry, function(error){onfail(error,'Get Destination Dir')});
function gotDestinationEntry(destination){
// move the file
targetImg.moveTo(destination, targetImg.name, moveSuccess, function(error){onfail(error,'Move Image')});
alert('dest :'+destination.fullPath);
};
function moveSuccess(){
alert('FILE MOVE SUCCESSFUL!');
};
}; //getImageURI
credit to: nbk on the google phonegap group.
Since you have the data in Base64 format you can just use the FileWriter to save the data to disk.
I think you need to capture the image as FILE_URL, and save the image to sdcard first as mentioned by Steven Benjamin above.
Then you can retrive the base64 DATA_URL as
function readFile() { // button onclick function
var gotFileEntry = function(fileEntry) {
console.log("got image file entry: " + fileEntry.fullPath);
fileEntry.file( function(file) {
var reader = new FileReader();
reader.onloadend = function(evt) {
console.log("Read complete!");
image64.value = evt.target.result;
};
reader.readAsDataURL(file);
}, failFile);
};
window.resolveLocalFileSystemURI("file:///mnt/sdcard/test.jpg", gotFileEntryImage, function(){console.log("* * * onPhotoURISuccess" + failed);});
}