Cached images when using cordova image picker includes "%" - android

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.

Related

ListView reusing old images

I created a plugin using Picasso and it uses the android.widget.ImageView to load the cached image into.
The plugin works fine if using a Repeater but whenever i try using it with a ListView after scrolling past about the 7th item the ListView begins to reuse old images even if the image source is different
The reason why is because list views reuse the entire fragment; so what happens is that your img being reused gets the old image shown unless you clear it.
I actually use Picasso myself; and this is my current picasso library.
So if you look in my code below, when I set the new .url, I clear the existing image. (I made a comment on the specific line) -- This way the image now show blank, and then picasso loads it from either memory, disk or a remote url (in my case a remote url) and it will assign the proper image.
"use strict";
var Img = require('ui/image').Image;
var application = require("application");
var PT = com.squareup.picasso.Target.extend("Target",{
_owner: null,
_url: null,
onBitmapLoaded: function(bitmap, from) {
// Since the actual image / target is cached; it is possible that the
// target will not match so we don't replace the image already seen
if (this._url !== this._owner._url) {
return;
}
this._owner.src = bitmap;
},
onBitmapFailed: function(ed) {
console.log("Failed File", this._url);
},
onPrepareLoad: function(ed) {
}
});
Object.defineProperty(Img.prototype, "url", {
get: function () {
return this._url;
},
set: function(src) {
if (src == null || src === "") {
this._url = "";
this.src = null;
return;
}
var dest = src;
this._url = dest;
this.src = null; // -- THIS IS THE LINE TO CLEAR THE IMAGE
try {
var target = new PT();
target._owner = this;
target._url = dest;
var x = com.squareup.picasso.Picasso.with(application.android.context).load(dest).into(target);
} catch (e) {
console.log("Exception",e);
}
},
enumerable: true,
configurable: true
});
Please note you only need to require this class once, then it attaches itself to the <Image> component and adds the new .url property; this allows me to use this in the Declarative XML in all the rest of the screens and when I need picasso, I just use the .url property to have picasso take over the loading of that image.

Loading binary image data to an image fails on Android 4.1 in Cordova Project

I have serious issues loading binary image data into a simple image-element. I coded a cordova app (using Sencha touch) which loads images the following way:
xhr.open('GET', imageUrl, true);
xhr.responseType = 'blob';
xhr.addEventListener('load', function () {
if (xhr.status === 200) {
// onload needed since Google Chrome doesn't support addEventListener for FileReader
fileReader.onload = function (evt) {
image.setSrc(evt.target.result);
};
// Load blob as Data URL
fileReader.readAsDataURL(xhr.response);
}
}, false);
On Android 5 and 4.4 (these are the ones I tested) it works like a charm. Now I ran it Android 4.1 on an ASUS Tablet and the onload callback doesn't get fired. When I throw a blob in the readAsDataURL-function, at least the onload callback is fired, but the image doesn't show any image as well :(
Has anyone a suggestion, what the failure could be or what I'm doing wrong?
Ah, finally I got it to work on Android 4.1.1 (ASUS Tablet) with the following code. Another issue was, that saving an arraybuffer response from the xhr could not simply serialized, so I converted the stuff to string. Also I receive the blob taking into account, that on some systems the Blob object simply isn't there:
function arrayBufferToString(buf) {
return String.fromCharCode.apply(null, new Uint8Array(buf));
};
function stringToArrayBuffer(str) {
var buf = new ArrayBuffer(str.length*2); // 2 bytes for each char
var bufView = new Uint8Array(buf);
for (var i=0, strLen=str.length; i<strLen; i++) {
bufView[i] = str.charCodeAt(i);
}
return buf;
};
function getBlob(content, type) {
var blob = null;
// Android 4 only has the deprecated BlobBuilder :-(
try {
blob = new Blob([content], {type: type});
} catch(e) {
window.BlobBuilder = window.BlobBuilder || window.WebKitBlobBuilder ||
window.MozBlobBuilder || window.MSBlobBuilder;
if (window.BlobBuilder)
{
var bb = new BlobBuilder();
bb.append(content);
blob = bb.getBlob(type);
}
}
return blob;
};
cachedFile = getCachedFile(...); // not of interest here, I think :-)
if (cachedFile)
{
callback.apply(this, [window.webkitURL.createObjectURL(getBlob(stringToArrayBuffer(cachedFile.data), 'image/jpeg'))]);
}
else {
xhr.open('GET', imageUrl, true);
xhr.responseType = 'arraybuffer';
xhr.addEventListener('load', function () {
if (xhr.status === 200) {
cachedFile = {
url: imageUrl,
data: arrayBufferToString(xhr.response)
};
addCachedFile(cachedFile); // not of interest here, I think :-)
callback.apply(this, [window.webkitURL.createObjectURL(getBlob(xhr.response, 'image/jpeg'))]);
}
}, false);
// Send XHR
xhr.send();
}
Edit: Just did a little change and now used the Uint8Array Class instead of the Uint16Array Class because I got errors: "RangeError: byte length of Uint16Array should be a multiple of 2". Now it works well.
Edit2: Just saw, that the above code doesn't work out in all situations because of the usage of Uint8Array resp. Uint16Array.
Now I think I have a solid solution: I convert the binary responded by the image url into a base64 using canvas with the function from here http://appcropolis.com/blog/web-technology/javascript-encode-images-dataurl/ . Takes a little time, but still a working solution :)

Downloading Transparent PNG's on Android using Appcelerator turns the background black

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>

jsPDF with Cordova - Adding images

I am trying to generate a PDF using the jsPDF library (https://github.com/MrRio/jsPDF) from within a mobile Cordova app. I am currently testing the app on an Android 4.0.4 device but it also needs to run on Windows mobile 8. The text in the PDF document is shown correctly however any images are scrambled. See image below
I did find this page (https://coderwall.com/p/nc8hia) that seemed to indicate there is a problem with jsPDF displaying images in Cordova (see comments) but the author never posted the follow-up. Has anyone been able to use jsPDF with Cordova and properly add images to the generated PDF? My code is below, any assistance or advice would be greatly appreciated.
function demoReceipt() {
var img = new Image();
img.onError = function() {
alert('Cannot load image: "' + url + '"');
};
img.onload = function() {
createPdf2(img);
};
img.src = 'img/testlogo.png';
}
function createPdf2(myLogo) {
// var doc = new jsPDF('p', 'pt', 'jontype');
var doc = new jsPDF('p', 'pt', 'letter');
doc.setProperties({
title : 'Fueling Receipt',
author : 'Jon Hoffman',
creater : 'Jon Hoffman'
});
doc.addImage(myLogo, 'PNG', 5, 5, 140, 30);
doc.setFontSize(12);
doc.text(10, 40, 'Sample PDF receipt');
doc.setFontSize(8);
doc.text(10, 45, 'Smaller text - new');
var pdfOutput = doc.output();
//NEXT SAVE IT TO THE DEVICE'S LOCAL FILE SYSTEM
//Requires cordova plugin add org.apache.cordova.file
console.log("file system...");
window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, function(fileSystem) {
console.log(fileSystem.name);
console.log(fileSystem.root.name);
console.log(fileSystem.root.fullPath);
fileSystem.root.getDirectory("myPDFs", {
create : true,
exclusive : false
}, function(dir) {
fileSystem.root.getFile("myPDFs/test.pdf", {
create : true
}, function(entry) {
var fileEntry = entry;
console.log(entry);
entry.createWriter(function(writer) {
writer.onwrite = function(evt) {
console.log("write success");
};
console.log("writing to file");
writer.write(pdfOutput);
}, function(error) {
console.log(error);
});
}, function(error) {
console.log(error);
});
}, function(error) {
});
}, function(event) {
console.log(evt.target.error.code);
});
}
I solved the issue with help from this blog post: https://coderwall.com/p/nc8hia. There does seems to be significant differences between the 0.90 version used in that post and the version that I am using from https://github.com/MrRio/jsPDF however the solution is pretty much the same.
First off, in the version from MyRio, you can get the PDF generation working without fixing the Blob issue noted in Igor’s post. All you need is to generate the PDF output by calling “doc.ouput()” and then save it using the Cordova filesystem plugin. So I thought I did not have to create the Blob (this is where I was wrong).
Igor (from the coderwall post) responded back to my question with some additional code but when I searched the jspdf.js file from MyRio version, I saw that the code (more compact version) was already in the code on lines 734 – 738:
var data = buildDocument(), len = data.length,
ab = new ArrayBuffer(len), u8 = new Uint8Array(ab);
while(len--) u8[len] = data.charCodeAt(len);
return new Blob([ab], { type : "application/pdf" });
But I also notice that the blob creation code that Igor fixed in his initial post was at the end of this block of code. So I commented out the “return new Blob([ab], { type : “application/pdf”});” line and put in the following code from Igor’s post with minor variable name changes:
try
{
var blob = new Blob([ab], {type: "application/pdf"});
console.debug("case 1");
return blob;
}
catch (e)
{
window.BlobBuilder = window.BlobBuilder ||
window.WebKitBlobBuilder ||
window.MozBlobBuilder ||
window.MSBlobBuilder;
if (e.name == 'TypeError' && window.BlobBuilder)
{
var bb = new BlobBuilder();
bb.append(ab);
console.debug("case 2");
return bb.getBlob("application/pdf");
}
else if (e.name == "InvalidStateError")
{
// InvalidStateError (tested on FF13 WinXP)
console.debug("case 3");
return new Blob([ab], {type: "application/pdf"});
}
else
{
// We're screwed, blob constructor unsupported entirely
console.debug("Errore");
}
}
Then when I generate that pdfOutput, in my code, I changed
var pdfOutput = doc.output();
to
var pdfOutput = doc.output(“blob”);
and it worked.
I hope this post is able to help out others experiencing the same issues.

How to move captured image in PhoneGap to a folder in sdcard

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);});
}

Categories

Resources