SAPUI5 How to decode qrcode from qrcode image - javascript

How to scan QRCode data from QRCode image(jpg/png) that is available in local System. From UI5 library im able to find BarcodeScanner. Using below code im able to open Camera from my device and able to scan the barcodes..
sap.ndc.BarcodeScanner.scan(
function(mResult) {
alert("We got a bar code\n" +
"Result: " + mResult.text + "\n" +
"Format: " + mResult.format + "\n" +
"Cancelled: " + mResult.cancelled);
},
function(Error) {
alert("Scanning failed: " + Error);
},
);
But how to decode QRCode image data? can someone please help me?
Thankyou in advance

You could use this lib for reading qr codes: https://github.com/LazarSoft/jsqrcode
In this function the file is read and the decoded result is outputted in a div container
function readFile(oFile) {
var input = oFile.target;
var reader = new FileReader();
reader.onload = function() {
var dataURL = reader.result;
decodeImageFromBase64(dataURL, function(decodedInformation) {
document.getElementById("output").innerHTML = decodedInformation;
})
};
reader.readAsDataURL(input.files[0]);
}
In this fuction the decoding magic is happen
function decodeImageFromBase64(data, callback) {
qrcode.callback = callback;
qrcode.decode(data)
}

Related

Cordova fileReader works for text, but returns null for jpgs

I'm using an emulation of an android nexus 9 for testing.
I run this code for text, and it works:
var filePath = cordova.file.dataDirectory + "files/newFile.txt";
window.resolveLocalFileSystemURL(filePath, gotFileEntry, fail);
function gotFileEntry(fileEntry) {
console.log("gotFileEntry: "+fileEntry.name); //"newFile.txt"
console.log("fileEntry fullpath: "+fileEntry.fullPath); //"/newFile.txt" - cause for concern?
fileEntry.file(gotFile, fail);
}
function gotFile(file){
console.log("Got the File");
console.log("Type: " + file.type); //text/plain
console.log("Path: " + file.fullPath); //undefined
//path wasn't defined, manually set it
file.fullPath = fullPath = cordova.file.dataDirectory + 'files/' + file.name;
console.log("Path: " + file.fullPath); //"file:///data/data/com.ionicframework.myproject123456/files/files/newFile.txt"
console.log("Bytes: " + file.size); //~14 bytes
var reader = new FileReader();
reader.onloadend = function(evt) {
console.log('Reader status "onloadend": '+reader.readyState); //2 (a.k.a loaded)
console.log('Result: '+evt.target.result); //"data:text/plain;base64,c26tZSBmaWx1IGrhdGE=" (success)
console.log('Result: '+reader.result); //"data:text/plain;base64,c26tZSBmaWx1IGrhdGE=" (success)
};
reader.onerror = function(e) {
console.log('Error.code: '+reader.error.code) //unused
console.log('Error.message: '+reader.error.message) //unused
}
console.log("Reader status before: "+reader.readyState); //0
reader.readAsDataURL(file);
console.log("Reader status after: "+reader.readyState); //1
}
So I switch it to try and use the picture. Same code, switching "newFile.txt" for "mypicture.jpg":
var filePath = cordova.file.dataDirectory + "files/mypicture.jpg";
window.resolveLocalFileSystemURL(filePath, gotFileEntry, fail);
function gotFileEntry(fileEntry) {
console.log("gotFileEntry: "+fileEntry.name); //"mypicture.jpg"
console.log("fileEntry fullpath: "+fileEntry.fullPath); //"/mypicture.jpg" - cause for concern?
fileEntry.file(gotFile, fail);
}
function gotFile(file){
console.log("Got the File");
console.log("Type: " + file.type); //image/jpeg
console.log("Path: " + file.fullPath); //undefined
//path wasn't defined, manually set it
file.fullPath = fullPath = cordova.file.dataDirectory + 'files/' + file.name;
console.log("Path: " + file.fullPath); //"file:///data/data/com.ionicframework.myproject123456/files/files/mypicture.jpg"
console.log("Bytes: " + file.size); //~3 mega bytes
var reader = new FileReader();
reader.onloadend = function(evt) {
console.log('Reader status "onloadend": '+reader.readyState); //2 (a.k.a loaded)
console.log('Result: '+evt.target.result); //"null" (FAILURE)
console.log('Result: '+reader.result); //"null" (FAILURE)
};
reader.onerror = function(e) {
console.log('Error.code: '+reader.error.code) //1 (NOT_FOUND_ERR?)
console.log('Error.message: '+reader.error.message) //undefined
}
console.log("Reader status before: "+reader.readyState); //0
reader.readAsDataURL(file);
console.log("Reader status after: "+reader.readyState); //1
}
Using "adb shell" I'm able to show the directory where the files are located. Both files are there. The permissions and owner of both files are the same.
My end goal is to read in a file as a base64 datastream and add it as an attachment to an email using katzer's emailComposer plugin. I'm hoping that I can use this method on an iOS deployment also.
How am I reading this image file incorrectly -- why is reader.readyState returning null?
Thanks in advance.
Figured it out.. It was a dunce mistake - the permissions of the image were changed when I overwrote the file when debugging something else.

How to insert image in sqlite?

I am developing a cross platform application using cordova.
I need to insert image inside sqlite. I am getting lots of code for android but I find it difficult to do with javascript. I am getting err.code:5 when I run the following code in my iPhone.
document.addEventListener("deviceready", onDeviceReady, false);
var img;
var currentRow;
var b = new Blob();
function previewFile() {
// var preview = document.querySelector('img');
var file = document.querySelector('input[type=file]').files[0];
var reader = new FileReader();
// var package_name = document.getElementById("pr").value;
reader.onloadend = function () {
// img = reader.result;
if(file.type.match('image.*'))
{
img = reader.result;
// ref.push({"image":image,"service":arr,"package_name":package_name});
}
else
{
alert("select an image file");
}
}
if (file) {
reader.readAsDataURL(file);
} else {
preview.src = "";
}
var image1 = encodeURI(img);
// var b = new Blob();
b = image1;
console.log(b);
console.log(image1);
//document.write('<img src="'+image+'"/>');
}
function onDeviceReady() {
var db = window.sqlitePlugin.openDatabase({name:"sqlite"});
db.transaction(populateDB, errorCB, successCB);
}
function populateDB(tx) {
tx.executeSql('CREATE TABLE IF NOT EXISTS DEMO (id INTEGER PRIMARY KEY AUTOINCREMENT, name,number,image BLOB)');
}
function insertDB(tx) {
tx.executeSql('INSERT INTO DEMO (name,number,image) VALUES ("' +document.getElementById("txtName").value
+'","'+document.getElementById("txtNumber").value+'","' +b+ '")');
}
function goInsert() {
var db = window.sqlitePlugin.openDatabase({name:"sqlite"});
db.transaction(insertDB, errorCB, successCB);
}
My html code:
<input type="file" onchange="previewFile()">
<button onclick="goInsert()">Insert</button>
How to do this. Can someone help me? Thanks in advance...
Convert your image (in memory) to a byte[] and then save it your sql db as varbinary(max).
Inserting blob into database will make your application slow as well as laggy, instead save the path of the selected picture into the database.
And when you want to upload the image to the server use
fileupload feature of cordova.
If you are getting image from server than download that image locally and save that path into the database
window.requestFileSystem(LocalFileSystem.PERSISTENT, 0,
function onFileSystemSuccess(fileSystem)
{
fileSystem.root.getFile(
"dummy.html", {create : true, exclusive : false},
function gotFileEntry(fileEntry)
{
var sPath = fileEntry.fullPath.replace("dummy.html", "");
var fileTransfer = new FileTransfer();
fileEntry.remove();
fileTransfer.download(
"http://www.w3.org/2011/web-apps-ws/papers/Nitobi.pdf",
sPath + "theFile.pdf",
function(theFile)
{
console.log("download complete: " + theFile.toURI());
showLink(theFile.toURI());
},
function(error)
{
console.log("download error source " + error.source);
console.log("download error target " + error.target);
console.log("upload error code: " + error.code);
}
);
}, fail);
}, fail);

Cordova App : How to get the actual path of file

I'm using Cordova to make android and iOS app, now I would like to check if file already exist in the dirctory.
First I download file from server and save it locally using the code below
$scope.downloadFile = function(){
alert(cordova.file.dataDirectory)
var fileTransfer = new FileTransfer();
var uri = encodeURI("http://example.com/files/th/001.mp3");
var downloadPath = cordova.file.dataDirectory+'001.mp3'; // ANDROID
fileTransfer.download(
uri,
downloadPath,
function(entry) {
$scope.savepath = entry.toInternalURL();
alert("download complete: " + entry.toURL());
alert('saved at : '+entry.toInternalURL());
},
function(error) {
alert("download error source " + error.source);
alert("download error target " + error.target);
alert("upload error code" + error.code);
},
false,
{
headers: {
"Authorization": "Basic dGVzdHVzZXJuYW1lOnRlc3RwYXNzd29yZA=="
}
}
);
}//End DownloadFile
and I would like to check if the file already exist using checkIfFileExists(path) method
function checkIfFileExists(path){
window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, function(fileSystem){
//alert('result: '+JSON.stringify(fileSystem.root))
fileSystem.root.getFile(path, { create: false }, fileExists, fileDoesNotExist);
}, getFSFail); //of requestFileSystem
}
function fileExists(fileEntry){
alert("File " + fileEntry.fullPath + " exists!");
}
function fileDoesNotExist(){
alert("file does not exist");
}
function getFSFail(evt) {
console.log(evt.target.error.code);
}
I checked on my phone, the file is already saved to Android/data/com.myname.myappname/file/001.mp3
but the problem is the code always show file does not exist whenever I use the path like
cordova.file.dataDirectory+'001.mp3';
or cdvfile://localhost/persistent/files/001.mp3
or 'cdvfile://localhost/files/001.mp3'
so I would like to ask that the real path that I need to use to check if the file exist or not.
Please provide me any suggestion.
Regards.
Do you need to use or CheckFileExists? You could try using Phonegap's FileReader method?
var reader = new FileReader();
var fileSource = cordova.file.dataDirectory+'001.mp3'
reader.onloadend = function(evt) {
if(evt.target.result == null) {
// Null? You still have a problem: file doesn't exist.
} else {
// Otherwise the file exists.
}
};
//Check if the file exists
reader.readAsDataURL(fileSource);

Real AJAX uploader - set file to upload manually

I used the Real Ajax Uploader (http://www.albanx.com/ajaxuploader) for uploading files from my js/jQuery based frontend to an ASP.net based server-side function - that works well by selecting files from the file-system as via the file dialog.
But now i need to find a way to set a file (i know the exact name and local path of the file) to upload automatically via a JS function instead of selecting it manually by clicking "select file" and selecting it from the file-dialog.
I think i have to manually create a file-object and push it into the files array (because of this description to get fiel infos : http://www.albanx.com/ajaxuploader/examples.php?e=6) but I can not manage setting a file and uploading it via my js function
Any help is highly appreciated
Thanks in advance
EDIT:
Thanks for responding Here is the code for taking a picture with the devices camera and pushing it into the files object of the uploader ...
that works so far, but i do not know how to update the fileuploader because it seems not to have a method to do this ...
so the file is in the file-list (file_list[0]) with all the parameters i think it dioes need, but it doesnt show up in the gui-file-list
regards Don
<code>
// photo functions
function getPhoto(){
navigator.camera.getPicture(onPhotoSuccess, onPhotoFail, {
quality: 50,
destinationType: Camera.DestinationType.NATIVE_URI
});
console.log("get photo ...");
}
function onPhotoSuccess(imageURI) {
console.log("photo taken ..." + imageURI);
$('#imgUploadArea').ajaxupload('clear');
var AU = $('#imgUploadArea').data('AU');
var file_list = AU.files; //get all the file objects
console.log("files: " + file_list.length);
// get the file object
window.resolveLocalFileSystemURL(imageURI, function(fileEntry) {
fileEntry.file(function(fileObj)
{
fileuploadShow("input.caseFormText.caseFormPhotoBtn");
// add the image
var capturedImg = new Object();
capturedImg.status = 0;
capturedImg.name = fileEntry.name;
capturedImg.path = fileEntry.fullPath;
capturedImg.size = fileObj.size;
capturedImg.filetype = "image.jpeg";
capturedImg.ext = "jpg";
capturedImg.AU = AU;
capturedImg.file = fileObj;
console.log("set image object to upload: " + capturedImg.path);
file_list.push(capturedImg);
console.log("files: " + file_list.length);
console.log("imgUpload ... imagedata path: " + file_list[0].path);
console.log("imgUpload ... imagedata name: " + file_list[0].name);
console.log("imgUpload ... imagedata status: " + file_list[0].status);
console.log("imgUpload ... imagedata size: " + file_list[0].size);
console.log("imgUpload ... imagedata filetype: " + file_list[0].filetype);
console.log("imgUpload ... imagedata ext: " + file_list[0].ext);
console.log("imgUpload ... imagedata file: " + JSON.stringify(file_list[0].file));
console.log("file added to filelist: " + file_list.length);
var files = $("#imgUploadArea").ajaxupload('getFiles');
console.log(JSON.stringify(files));
//$("#imgUploadArea").ajaxupload.('renderHtml');
//$("#imgUploadArea").ajaxupload('start');
});
});
}
function onPhotoFail(message) {
alert('Photo failed because: ' + message);
}
</code>
Don

JS - File Reader API get image file size and dimensions

Hi i'm using the following code to get the upload image using File Reader API:
<script type="text/javascript">
var loadImageFile = (function () {
if (window.FileReader) {
var oPreviewImg = null, oFReader = new window.FileReader(),
rFilter = /^(?:image\/bmp|image\/cis\-cod|image\/gif|image\/ief|image\/jpeg|image\/jpeg|image\/jpeg|image\/pipeg|image\/png|image\/svg\+xml|image\/tiff|image\/x\-cmu\-raster|image\/x\-cmx|image\/x\-icon|image\/x\-portable\-anymap|image\/x\-portable\-bitmap|image\/x\-portable\-graymap|image\/x\-portable\-pixmap|image\/x\-rgb|image\/x\-xbitmap|image\/x\-xpixmap|image\/x\-xwindowdump)$/i;
oFReader.onload = function (oFREvent) {
/*get image*/
var _img = oFREvent.target.result;
console.log(oFREvent.target);
/*add img to hidden input text*/
localStorage.photo = _img;
oPreviewImg.src = oFREvent.target.result;
};
return function () {
var aFiles = document.getElementById("imageInput").files;
if (aFiles.length === 0) { return; }
if (!rFilter.test(aFiles[0].type)) {
notify("You must select a valid image file!",3400,false); return;
}
oFReader.readAsDataURL(aFiles[0]);
}
}
})();
</script>
<form name="uploadForm">
<p><input id="imageInput" type="file" name="myPhoto" onchange="loadImageFile();" /><br />
<input type="submit" value="Send" /></p>
<input type="hidden" id="photo_1_hidden" name="photo_1"/>
</form>
it works great and it returns the base64 data of the image.
now i would like to get also the image file size and the image width and height.
Is it possible?
I tryed to log in console the file but i can't find what i'm searching for.
Any help appriciated thanks so much!
Something like this?
var oPreviewImg = new Image();
oPreviewImg.onload = function(){
console.log(this.size);
alert("'" + this.name + "' is " + this.width + " by " + this.height + " pixels in size.");
return true;
};
oPreviewImg.onerror = function(){
alert("'" + this.name + "' failed to load.");
return true;
}
oPreviewImg.src = "//placeholdit.imgix.net/~text?txtsize=33&txt=350%C3%97150&w=350&h=150";
var xhr = new XMLHttpRequest();
xhr.open('HEAD', oPreviewImg.src, true);
xhr.onreadystatechange = function() {
console.log('this', this);
if ( xhr.readyState == 4 ) {
if ( xhr.status == 200 ) {
alert('Size in bytes: ' + xhr.getResponseHeader('Content-Length'));
} else {
alert('ERROR');
}
}
};
xhr.send(null);
Live version
Update Live version replaced with Fiddle, however, due to cross site scripting concerns, the size is no longer being retrieved effectively.
const reader = new FileReader()
reader.onload = (theFile) => {
const image = new Image()
image.src = theFile.target.result
image.onload = () => {
console.log('image width ===== ' + image.width + 'Image height
===== ' + image.height)
}
}
reader.readAsDataURL(item)
I don't believe that JS is going to be capable of getting that data without first rendering the image to the viewport. That is to say, I am unfamiliar of any method that would do what you ask in the JavaScript, or JQuery libraries. Your best bet for getting data like that is going to be rendering the image to the page in a preview capacity or using a more powerful language like PHP and using an Ajax request to get the data you're looking for.

Categories

Resources