Retrieve Image from File Path and Encode it to Base64 - javascript

I need to convert Base64 from provided image file path. Following are conversion codes:
var encodeImageUri = function(imageUri, callback) {
var c = document.createElement('canvas');
var ctx = c.getContext("2d");
var img = new Image();
img.onload = function() {
c.width = this.width;
c.height = this.height;
ctx.drawImage(img, 0, 0);
if(typeof callback === 'function'){
var dataURL = c.toDataURL("image/jpeg");
callback(dataURL);
}
};
img.src = imageUri;
}
function getFileContentAsBase64(path,callback){
console.log(path);
window.resolveLocalFileSystemURL(path, gotFile, fail);
function fail(e) {
alert(JSON.stringify(e));
}
function gotFile(fileEntry) {
fileEntry.file(function(file) {
var reader = new FileReader();
reader.onloadend = function(e) {
var content = this.result;
callback(content);
};
// The most important point, use the readAsDatURL Method from the file plugin
reader.readAsDataURL(file);
});
}
}
How I use it:
var image = 'file://' + path;
getFileContentAsBase64(image, function (base64File) {});
encodeImageUri(image, function(base64){});
path example:
file:///storage/emulated/0/test.jpeg
If I print base64 result to Code Beautifier, one is corrupted with 3kb size only, and other 1 is error with broken image icon.

Related

Image dimensions not reflected correctly

I am trying to get the base64 of some images in Javascript and was using this function:
function getBase64Image(img) {
return new Promise((data) => {
var canvas = document.createElement("canvas");
canvas.width = img.naturalWidth;
canvas.height = img.naturalHeight;
var ctx = canvas.getContext("2d");
ctx.drawImage(img, 0, 0);
data(canvas.toDataURL("image/png").replace(/^data:image\/(png|jpg|jpeg);base64,/, ""))
})
}
Then I call the function to load in the image using:
var img = new Image();
img.crossOrigin = 'Anonymous';
img.onload = function () {
getBase64Image(this).then(data => {})
}
img.src = wha[1][0]
If I look at the naturalWidth of the image (96px), it is different from the actual image itself (640px). I had been looking at other methods of getting base64 from an image but they also return the same results.

JSON to PNG Empty picture

Need help with my function to download a PNG from a SVG.
I read many similar post about that but don't succeed to apply to my code.
The image that I download is empty ...
My code :
function downloadCarteJPEG(nom,dpi) {
var svg = document.querySelector("svg");
var svgData = "";
if (typeof window.XMLSerializer != "undefined") {
svgData = (new XMLSerializer()).serializeToString(svg);
} else {
console.error("XMLSerializer undefined");
return;
}
var canvas = document.createElement("canvas");
var ctx = canvas.getContext("2d");
var svgSize = svg.getBoundingClientRect();
canvas.width = svgSize.width * dpi / 25.4;
canvas.height = svgSize.height * dpi / 25.4;
var data = btoa(unescape(encodeURIComponent(svgData)));
data = 'data:image/svg+xml;base64,' + data;
var image = document.createElement("img");
image.onload = function() {
ctx.drawImage(image, 0, 0);
var link = document.createElement("a");
link.download = nom;
link.href = canvas.toDataURL("image/png");
document.querySelector("body").appendChild(link);
link.click();
document.querySelector("body").removeChild(link);
};
image.src = data;
console.log("EXIT");
}

convert image from cordova imagepicker to base64

I am using the following snippet for my conversion operation (images from cordova image picker to base64 and store them in an array) but due to the async behavior, it is assigning same string as of the first image to all images. I tried while loop but then, the app crashed. Any suggestion how can I solve this problem.
Edit: results[ 0 ] is defined but all other results[ i ] are 'undefined', hence image source remains same for all iteration
window.imagePicker.getPictures(
function(results) {
for (var i = 0; i < results.length; i++) {
var img = new Image();
img.crossOrigin = 'Anonymous';
img.src = results[i];
img.onload = function(){
var canvas = <HTMLCanvasElement>document.createElement('canvas');
var ctx = canvas.getContext('2d');
canvas.height = img.height;
canvas.width = img.width;
ctx.drawImage( img, 0, 0);
var dataURL = canvas.toDataURL('image/jpeg').slice(23);
Attachments.push(dataURL); // array for storing base64 equivalent of all images
canvas = null;
};
}
img.src = results[ i ] starts reading the file at results[ i ] async, so when loop continues for i=1, results[ 1 ] is undefined because the file system is still reading for results[0]. Hence all iteration returns dataURL of the first image.
To avoid it use callbacks which solve this problem with the concept of closures.
window.imagePicker.getPictures(
function(results) {
console.log(results);
for (var i = 0; i < results.length; i++) {
parent.tobase64(results[i],function(dataURL){
parent.email_data.Attachments.push(dataURL);
});
}
}, function (error) {
console.log('Error: ' + error);
}
}
tobase64(file,callback){
var parent=this;
var img = new Image();
img.crossOrigin = 'Anonymous';
img.src = file;
img.onload = function(){
var canvas = <HTMLCanvasElement>document.createElement('canvas');
var ctx = canvas.getContext('2d');
canvas.height = img.height;
canvas.width = img.width;
ctx.drawImage( img, 0, 0);
var dataURL = canvas.toDataURL('image/jpeg').slice(23);
canvas = null;
callback.call(this,dataURL);
}
}

Why my code to convert any image to a Base64 string is not working?

I am trying to convert any image to a Base64 String but not getting the output
See the screenshot what I am getting
Screenshot
Javascript code
function encodeImageFileAsURL(cb)
{
return function()
{
var file = this.files[0];
var reader = new FileReader();
reader.onloadend = function ()
{
cb(reader.result);
}
reader.readAsDataURL(file);
}
}
$('#inputFileToLoad').change(encodeImageFileAsURL(function(base64Img)
{
$('.output')
.find('textarea')
.val(base64Img)
.end()
.find('a')
.attr('href', base64Img)
.text(base64Img)
.end()
.find('img')
.attr('src', base64Img);
}));
Basic example to convert to base64:
function toBase64(src, callback) {
var canvas = document.createElement('canvas'),
ctx = canvas.getContext('2d'),
img = new Image();
img.onload = function() {
canvas.width = img.width;
canvas.height = img.height;
ctx.drawImage(img, 0, 0, img.width, img.height);
callback(canvas.toDataURL());
}
img.src = src;
}

How to Draw an image on canvas from a byte array in jpeg or png format

Like the title says, I have a byte array representing the contents of an image (can be jpeg or png).
I want to draw that on a regular canvas object
<canvas id='thecanvas'></canvas>
How can I do that?
UPDATE I tried this (unsuccesfully):
(imgData is a png sent as a byte array "as is" through WebSockify to the client)
function draw(imgData) {
"use strict";
var canvas = document.getElementById("myCanvas");
var ctx = canvas.getContext("2d");
var rdr = new FileReader();
var imgBlob = new Blob([imgData], {type: "image/png"});
rdr.readAsBinaryString(imgBlob);
rdr.onload = function (data) {
console.log("Filereader success");
var img = new Image();
img.onload = function () {
console.log("Image Onload");
ctx.drawImage(img, 0, 0, canvas.width, canvas.height);
};
img.onerror = function (stuff) {
console.log("Img Onerror:", stuff);
};
img.src = "data:image/png;base64," + window.btoa(rdr.result);
};
}
I always reach img.onerror()
Also After reading the file with a HEX editor on my file system, I can see that the byte array is identical to the original file.
This Works:
function draw2(imgData, coords) {
"use strict";
var canvas = document.getElementById("myCanvas");
var ctx = canvas.getContext("2d");
//var uInt8Array = new Uint8Array(imgData);
var uInt8Array = imgData;
var i = uInt8Array.length;
var binaryString = [i];
while (i--) {
binaryString[i] = String.fromCharCode(uInt8Array[i]);
}
var data = binaryString.join('');
var base64 = window.btoa(data);
var img = new Image();
img.src = "data:image/png;base64," + base64;
img.onload = function () {
console.log("Image Onload");
ctx.drawImage(img, coords[0], coords[1], canvas.width, canvas.height);
};
img.onerror = function (stuff) {
console.log("Img Onerror:", stuff);
};
}

Categories