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);});
}
Related
I am trying to process images from my gallery using the cordova imagepicker plugin. Here is my code:
$scope.getProductImage = function() {
// Image picker will load images according to these settings
var options = {
maximumImagesCount: 1, // Max number of selected images, I'm using only one for this example
quality: 80 // Higher is better
};
$cordovaImagePicker.getPictures(options).then(function (imageData) {
// Loop through acquired images
for (var i = 0; i < imageData.length; i++) {
$scope.sourceDirectory = imageData[i].substring(0, imageData[i].lastIndexOf('/') + 1);
$scope.sourceFileName = imageData[i].substring(imageData[i].lastIndexOf('/') + 1, imageData[i].length);
$scope.fileName = $scope.sourceDirectory + $scope.sourceFileName
}
}, function(error) {
console.log(error);
// In case of error
});
};
However, some images return a $scope.sourceFileName that contains a "%". This causes the moveFile in the cordova file plugin to fail with error code 1. Other images that does not contain the "%" is being processed correctly. Any ideas on why this is?
turns out it's a space replaced by "%20". I just did a string replace and it worked.
I'm creating an Hybrid app in which I want to upload video to
server. Sometimes it uploads the video to the server but most of the
time Plugin shows the uploading progress to 99% and then it gives
null in success callback.
Thanks in advance. :-)
/********* OPENING CAMERA TO CPTURE VIDEO ***********/
function make_Video()
{
// capture callback
var captureSuccess = function(mediaFiles) {
var i, len , video_path;
if(mediaFiles.length > 0)
{
for (i = 0, len = mediaFiles.length; i < len; i += 1)
{
video_path = mediaFiles[i].fullPath;
Upload_Video(video_path);
}
}
};
// capture error callback
var captureError = function(error)
{
console.log('Error Code: ' + error.code);
};
navigator.device.capture.captureVideo(captureSuccess, captureError, { quality: 100,destinationType: Camera.DestinationType.FILE_URI });
}
/****************STORING VIDEO ON SERVER******************/
function Upload_Video(video_path)
{
var server = server_link; // MY SERVER LINK
var params = {'user_id':logged_in_user_id,'action':'update_intro_video'};
if (server)
{
// Specify transfer options
$('#modal_first_line').text(0+" %"+" Uploaded");
$('#new_modal').show();
var options = new FileUploadOptions();
options.fileKey = "user_video";
options.fileName = video_path.substr(video_path.lastIndexOf('/')+1);
options.mimeType = "video/mp4";
options.chunkedMode = false;
options.httpMethod = "POST";
options.params = params;
// Transfer picture to server
var ft = new FileTransfer();
//progree bar
ft.onprogress = function(progressEvent) {
if (progressEvent.lengthComputable){ var perc = Math.floor(progressEvent.loaded / progressEvent.total * 100); $('#modal_first_line').text(perc+" %"+"
Uploaded"); } else {$('#new_modal').hide();
console.log("sorry! Upload Failed..."); } };
ft.upload(video_path, encodeURI(server) , function(data) {
$('#new_modal').hide();
console.log("SERVER RESPONSE: " + JSON.stringify(data));
},
function(error)
{
$('#new_modal').hide();
console.log("sorry! Upload Failed...");
}, options);
}
else{
$('#new_modal').hide();
console.log("sorry! Can't Upload File.");;
}
}
Solved.
The Problem was at server end. Configuration was making
trouble. post_max_size was set to 8Mb, so when limit of video
exceeds to 8MB, server was not allowing to save the video. I
increased the post_max_size to 100MB. To Increase the post_max_size
, I did the following steps
1. I Created a file .user.ini in the root directory
2. I placed the following code inside this file
file_uploads = O post_max_size = 100M upload_max_filesize
= 200M
Hope it will help someone.
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 have been struggling with Phonegap and Photoswipe. Here is what I have:
1) Currently I am requesting remote images via a php JSON call (working)
2) JSON images are returned and store locally to the Android device(working)
3) All images show up on Photswipe thumbnail gallery page (working)
problem is here
4) when I click on a thumbnail image, I'm not getting the Photoswipe gallery format, it just loads an the image to a blank page.
My guess is the photoswipe script is loading before I have completely passed all the images to the <#gallery
My question is how to re-initialize Photoswipe to read all the images or how to attached the Photoswipe function to the images that are appended to the
I'm trying to post the code I have working now, having trouble with the formatting here.
//Global instance of DirectoryEntry for our data
var DATADIR;
var knownfiles = [];
//Loaded my file system, now let's get a directory entry for where I'll store my crap
function onFSSuccess(fileSystem) {
fileSystem.root.getDirectory("Android/data/com.moto.photoloader",create:true,exclusive:false},gotDir,onError);
}
//The directory entry callback
function gotDir(d){
console.log("got dir");
DATADIR = d;
var reader = DATADIR.createReader();
reader.readEntries(function(d){
gotFiles(d);
appReady();
},onError);
}
//Result of reading my directory
function gotFiles(entries) {
console.log("The dir has "+entries.length+" entries.");
for (var i=0; i<entries.length; i++) {
console.log(entries[i].name+' dir? '+entries[i].isDirectory);
knownfiles.push(entries[i].name);
renderPicture(entries[i].fullPath);
}
}
function renderPicture(path){
$("#Gallery").append("<li><a href='"http://myurltofullimages"'><img src='"+path+"' alt=\"Image 018\"/></a></li>");
console.log("<li><a href='"/myurltofullimages"'><img src='"+path+"' alt=\"Image 018\"/></a></li>");
}
function onError(e){
console.log("ERROR");
console.log(JSON.stringify(e));
}
function onDeviceReady() {
//what do we have in cache already?
$("#status").html("Checking your local cache....");
window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, onFSSuccess, null);
}
function appReady(){
$("#status").html("Ready to check remote files...");
$.get("http://myurltojsonphp/photo_upload/json.php", {}, function(res) {
if (res.length > 0) {
$("#status").html("Going to sync some images...");
for (var i = 0; i < res.length; i++) {
if (knownfiles.indexOf(res[i]) == -1) {
console.log("need to download " + res[i]);
var ft = new FileTransfer();
var dlPath = DATADIR.fullPath + "/" + res[i];
console.log("downloading crap to " + dlPath);
ft.download("http://myurl/photo_upload/am/woman/thumb/" + escape(res[i]), dlPath, function(){
renderPicture(e.fullPath);
console.log("Successful download of "+e.fullPath);
}, onError);
}
}
}
$("#status").html("");
}, "json");
}
{
document.addEventListener("deviceready", onDeviceReady, true);
}
</script>
<script type="text/javascript">
(function(window, PhotoSwipe){
document.addEventListener('DOMContentLoaded', function(){
var
options = {},
instance = PhotoSwipe.attach( window.document.querySelectorAll('#Gallery a'), options );
}, false);
}(window, window.Code.PhotoSwipe));
</script>
After receiving the photos by the GET call, you must initialize photoswipe gallery:
$("ul.gallery a").photoSwipe(
{
allowUserZoom: false,
jQueryMobile: true,
autoStartSlideshow: false,
backButtonHideEnabled: false,
captionAndToolbarAutoHideDelay: 0,
preventSlideshow: true
});