Can't convert base64Image to ImageData object - javascript

I'm currently trying to convert a base64Encoded string (representation of an image) into an ImageData object in Javascript. However, this comes back with an error:
Uncaught InvalidStateError: Failed to construct 'ImageData': The input data length is not a multiple of 4.
The encoded image is 940 x 740
What am I missing? Any help appreciated
JSFiddle link with full code
function _base64ToArrayBuffer(base64) {
var binary_string = window.atob(base64);
var len = binary_string.length;
var bytes = new Uint8Array(len);
for (var i = 0; i < len; i++) {
bytes[i] = binary_string.charCodeAt(i);
}
return bytes.buffer;
}
const base64String = ""; //truncated because stackoverflow question too long.
const arrBuffer = _base64ToArrayBuffer (base64String );
var array = new Uint8ClampedArray(arrBuffer);
console.log(array);
var image = new ImageData(array, 900, 740);
console.log(image);

You can get the ImageData from a Canvas
function _base64ToImageData(buffer, width, height) {
return new Promise(resolve => {
var image = new Image();
image.addEventListener('load', function (e) {
var canvasElement = document.createElement('canvas');
canvasElement.width = width;
canvasElement.height = height;
var context = canvasElement.getContext('2d');
context.drawImage(e.target, 0, 0, width, height);
resolve(context.getImageData(0, 0, width, height));
});
image.src = 'data:image/png;base64,' + buffer;
document.body.appendChild(image);
setTimeout(() => {
document.body.removeChild(image);
}, 1);
});
}
window.addEventListener('load', () => {
_base64ToImageData(base64String, 2056, 1236).then(data => {
console.log(data);
});
});

Related

How to return a value from event listener's callback function [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 1 year ago.
Here's a bit about function:
This function takes the file object from html input tag and according to the quality value passed it compresses the image on the browser itself and this compressed image is used to upload to the server. the problem here is that I am not able to return the compressed file object which is generated inside a callback function passed into eventlistner in the following code.
Here's the function definition:
function compress_image_file(image_file_object, quality) {
const file = image_file_object;
const file_name = file.name.replace(/\.[^/.]+$/, "");
var data_url = '';
const reader = new FileReader();
reader.readAsDataURL(file);
if (reader.readyState == 2) {
console.log('readyState = 2');
}
reader.addEventListener("load", function () {
//convert file to base 64 string
data_url = reader.result;
//create a temp image
image = new Image();
image.src = data_url;
//calculate new sizes for the new image
new_width = image.width * quality / 100;
new_height = image.height * quality / 100;
//create a canvas
canvas = document.createElement("canvas");
//setting canvas size
canvas.width = new_width;
canvas.height = new_height;
ctx = canvas.getContext("2d");
ctx.drawImage(image, 0, 0, new_width, new_height);
//convert new image to data url
newDataUrl = canvas.toDataURL();
//convert data url to file
var arr = newDataUrl.split(',');
var mime = arr[0].match(/:(.*?);/)[1];
var ext = '.' + mime.split('/')[1];
//decode the base-64 image
var bstr = atob(arr[1]);
var n = bstr.length;
var u8arr = new Uint8Array(n);
while (n--) {
u8arr[n] = bstr.charCodeAt(n);
}
var new_file = new File([u8arr], file_name + ext, { type: mime });
})
// I am trying to return the value of new_file
}
here is how I want to implement the above function
var file_object = input.files[0]
var new_file = compress_image_file(file_object, 50)
console.log(new_file) // undefined
instead of undefined how can I get the file object in var new_file
You cannot return a value from an event listener. You can promisefy your FileReader and return the value from it.
async function compress_image_file(image_file_object, quality) {
try {
const file = image_file_object;
const file_name = file.name.replace(/\.[^/.]+$/, "");
var data_url = "";
const reader = new FileReader();
reader.readAsDataURL(file);
//convert file to base 64 string
data_url = await readFile(file);
//create a temp image
image = new Image();
image.src = data_url;
//calculate new sizes for the new image
new_width = (image.width * quality) / 100;
new_height = (image.height * quality) / 100;
//create a canvas
canvas = document.createElement("canvas");
//setting canvas size
canvas.width = new_width;
canvas.height = new_height;
ctx = canvas.getContext("2d");
ctx.drawImage(image, 0, 0, new_width, new_height);
//convert new image to data url
newDataUrl = canvas.toDataURL();
//convert data url to file
var arr = newDataUrl.split(",");
var mime = arr[0].match(/:(.*?);/)[1];
var ext = "." + mime.split("/")[1];
//decode the base-64 image
var bstr = atob(arr[1]);
var n = bstr.length;
var u8arr = new Uint8Array(n);
while (n--) {
u8arr[n] = bstr.charCodeAt(n);
}
var new_file = new File([u8arr], file_name + ext, { type: mime });
//return the value of new_file
return new_file;
} catch (err) {
throw new Error(err);
}
}
function readFile(file) {
return new Promise((resolve, reject) => {
var fr = new FileReader();
fr.readAsDataURL(file);
fr.onload = () => {
resolve(fr.result);
};
fr.onerror = reject;
});
}
var file_object = input.files[0];
compress_image_file(file_object, 50)
.then(new_file => {
console.log(new_file);
})
.catch(console.log);

Javascript FormData() File Upload to S3 works in Chrome but not in Safari

Working on a web app, I have image files going directly to the S3 bucket from the browser. This works well in Chrome, but in Safari there are no errors, but the code ends up uploading an empty file to the S3 bucket. Everything basically looks like it works in Safari, the S3 server even returns a 204 successful http response, and the file looks like it is in the bucket (but has a size of 0 bytes).
I debugging, and the blobData has size 55747 in Chrome but only size 47560 in Safari for the same image. Also, I have found what looks slightly different is in the networking section dev tools:
Chrome - working (204 response has positive size ~ 534B):
Safari - not working with empty file ( size column shows just a dash line )
Here is the JS upload code:
function uploadFile(data_url, s3Data, url, filename, id, thumbnail_url){
var xhr = new XMLHttpRequest();
xhr.open("POST", s3Data.url);
var postData = new FormData();
for(key in s3Data.fields){
postData.append(key, s3Data.fields[key]);
}
var blobData = dataURItoBlob(data_url);
postData.append('file', new File([blobData], filename));
xhr.onreadystatechange = function() {
if(xhr.readyState === 4){
if(xhr.status === 200 || xhr.status === 204){
setTimeout(function(){
$('#photo_container').append('<div id="image_container_'+id+'" class="hover-card mdl-cell--3-col-desktop mdl-cell--2-col-tablet mdl-cell--2-col-phone mdl-shadow--2dp"></div>');
$('.star-image').unbind('click').click( star_image_click );
$('.close-image').unbind('click').click(remove_image_click);
loading_files -= 1;
if ( loading_files == 0 ) {
$('#photo_load_spinner').removeClass('is-active');
$('#photo_load_text').text("");
}else{
$('#photo_load_text').text(loading_files+" files loading. Please wait.");
}
}, 1000);
}else{
alert("Could not upload file. "+xhr.responseText);
}
}
};
xhr.send(postData);
}
function dataURItoBlob(dataURI) {
var binary = atob(dataURI.split(',')[1]);
var array = [];
for(var i = 0; i < binary.length; i++) {
array.push(binary.charCodeAt(i));
}
return new Blob([new Uint8Array(array)], {type: 'image/png'});
}
I am kind of at a loss as to what to look for next. Any help would be greatly appreciated. Thanks!
EDIT
Just figure I should give a little more information. The data_url is generated from a canvas element which I use to resize the image in the browser, although I have confirmed that the canvas shows the image correctly in safari before upload. Here is that code:
function ResizeFile(raw_file) {
var reader = new FileReader();
reader.onload = function(e) {
var img = document.createElement("img");
img.onload = function() {
var canvas = document.createElement('canvas');
var ctx = canvas.getContext("2d");
//ctx.drawImage(img, 0, 0);
var MAX = 1200;
var width = img.width;
var height = img.height;
if (width > height) {
if (width > MAX) {
height *= MAX / width;
width = MAX;
}
} else {
if (height > MAX) {
width *= MAX / height;
height = MAX;
}
}
canvas.width = width;
canvas.height = height;
ctx.drawImage(img, 0, 0, img.width, img.height, 0, 0, width, height);
var dataurl = canvas.toDataURL("image/png");
getSignedRequest(dataurl);
}
img.src = e.target.result;
}
reader.readAsDataURL(raw_file);
}
We could resize image file and upload to server. Tested on Chrome and Safari, both works fine.
fileChange() {
var fileInputTag = document.getElementById("myFile");
if ('files' in fileInputTag) {
if (fileInputTag.files.length > 0) {
var file = fileInputTag.files[0];
var type = 'image/jpeg',
maxWidth = 800,
maxHeight = 600,
quality = 0.5,
ratio = 1,
canvas = document.createElement('canvas'),
context = canvas['getContext']('2d'),
canvasCopy = document.createElement('canvas'),
copyContext = canvasCopy.getContext('2d'),
img = new Image();
img.onload = function () {
if (img.width > maxWidth) {
ratio = maxWidth / img.width;
} else if (img.height > maxHeight) {
ratio = maxHeight / img.height;
}
canvasCopy.width = img.width;
canvasCopy.height = img.height;
copyContext.drawImage(img, 0, 0);
canvas.width = img.width * ratio;
canvas.height = img.height * ratio;
context.drawImage(canvasCopy, 0, 0, canvasCopy.width, canvasCopy.height, 0, 0, canvas.width, canvas.height);
canvas.toBlob((blob) => {
blob['name'] = file.name.split('.')[0] + '.jpeg';
var formData:FormData = new FormData();
formData.append('uploadFile', blob, blob.name);
// do upload here
}, type, quality);
};
img.src = URL.createObjectURL(file);
}
}
}
Add this to index.html or execute it before above script execution
if (!HTMLCanvasElement.prototype.toBlob) {
Object.defineProperty(HTMLCanvasElement.prototype, 'toBlob', {
value: function (callback, type, quality) {
var binStr = atob( this.toDataURL(type, quality).split(',')[1] ),
len = binStr.length,
arr = new Uint8Array(len);
for (var i = 0; i < len; i++ ) {
arr[i] = binStr.charCodeAt(i);
}
callback( new Blob( [arr], {type: type || 'image/png'} ) );
}
});
}
I remember Safari having limited support for FormData objects, for example:
https://developer.mozilla.org/en-US/docs/Web/API/FormData/set
https://developer.mozilla.org/en-US/docs/Web/API/FormData/get

Merge two dataURIs to create a single image

I want to generate images consisting of a label and an icon. The label part is going to vary a lot (50-100) while there are about 10 icons. I would like to make the final images in a modular way by splitting the final image in two parts, a label image and an icon image. I will build a service that returns dataURI for the labels while the icon dataURIs will be embedded in the page. Then I would like to combine these two different dataURIs to create a single dataURI representing a combined image.
How can I do this on the client side?
You can create images using your data uris and then draw a new image that includes them using canvas. Here's a simple example:
var nloaded = 0;
function checkload(event) {
nloaded++;
if (nloaded < 2) {
return;
}
var canvas = document.querySelector('canvas');
var context = canvas.getContext('2d');
context.drawImage(image1, 0, 0, 50, 50);
context.drawImage(image2, 50, 50, 100, 100);
var combined = new Image;
combined.src = canvas.toDataURL('data/gif');
document.body.appendChild(combined);
}
var image1 = new Image;
image1.onload = checkload;
image1.src = 'data:image/gif;base64,R0lGODdhAgACALMAAAAAAP///wAAAAAAAP8AAAAAAAAAAAAAAAAA/wAAAAAAAAAAAAAAAAAAAAAAAAAAACwAAAAAAgACAAAEAxBJFAA7';
var image2 = new Image;
image2.onload = checkload;
image2.src = 'data:image/gif;base64,R0lGODdhAgACALMAAAAAAP///wAAAAAAAP8AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACwAAAAAAgACAAAEA5BIEgA7';
canvas {
display: none;
}
<canvas width=100 height=100></canvas>
.
Once you have the images loaded from the data URI and combined using the drawImage commands of the canvas context you can use the canvas to create a new image like:
var combined = new Image;
combined.src = canvas.toDataURL('data/gif');
Unfortunately this won't work in IE8.
Example using an array of image objects containing URI src and x, y offsets:
var images = [
{ src: 'data:image/gif;base64,R0lGODdhAgACALMAAAAAAP///wAAAAAAAP8AAAAAAAAAAAAAAAAA/wAAAAAAAAAAAAAAAAAAAAAAAAAAACwAAAAAAgACAAAEAxBJFAA7', x: 0, y: 0 },
{ src: 'data:image/gif;base64,R0lGODdhAgACALMAAAAAAP///wAAAAAAAP8AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACwAAAAAAgACAAAEA5BIEgA7', x: 20, y: 20 },
];
var canvas = document.createElement('canvas');
var destination = document.getElementById('canvas');
Promise.all(images.map(imageObj => add2canvas(canvas, imageObj)))
.then(() => destination.append(canvas));
function add2canvas(canvas, imageObj) {
return new Promise( (resolve, reject) => {
if (!imageObj || typeof imageObj != 'object') return reject();
var image = new Image();
image.onload = function () {
canvas.getContext('2d')
.drawImage(this, imageObj.x || 0, imageObj.y || 0);
resolve();
};
image.src = imageObj.src;
});
}
Some more bells/whistles... function to generate a composite png:
function mergeImageURIs(images) {
return new Promise( (resolve, reject) => {
var canvas = document.createElement('canvas');
canvas.width = 1000; // desired width of merged images
canvas.height = 1000; // desired height of merged images
Promise.all(images.map(imageObj => add2canvas(canvas, imageObj))).then(() => resolve(canvas.toDataURL('image/png'), reject));
});
}
function add2canvas(canvas, imageObj) {
return new Promise( (resolve, reject) => {
if (!imageObj || typeof imageObj != 'object') return reject();
var x = imageObj.x && canvas.width ? (imageObj.x >=0 ? imageObj.x : canvas.width + imageObj.x) : 0;
var y = imageObj.y && canvas.height ? (imageObj.y >=0 ? imageObj.y : canvas.height + imageObj.y) : 0;
var image = new Image();
image.onload = function () {
canvas.getContext('2d').drawImage(this, x, y);
resolve();
};
image.src = imageObj.src;
});
}

Converting images to base64 within a loop before adding to jspdf - javascript

I have researched issues with the base64 conversion and jspdf function quite a bit. ( PS this is my first question on stackoverflow, please bare with any rookie mistakes ).
All seems to work fine with the below code except that the pdf is generated and saved before the loop where the images are converted to base64 and placed to the document is finished. I added a couple alerts to check timing. Would the solution be to check when the loop is finished, the images placed before continuing with the pdf function? if so, how? please help.
$(document).ready(function(){
$("a#getdoc").click(function(){
var doc = new jsPDF('landscape, in, legal');
var myimages = 'img1.jpg|img2.jpg|img3.png';
var myimgarray = myimages.split('|');
function convertImgToBase64(url, callback, outputFormat){
var canvas = document.createElement("canvas");
canvas.width = img.width;
canvas.height = img.height;
var ctx = canvas.getContext("2d");
ctx.drawImage(img, 0, 0);
return canvas.toDataURL("image/jpeg");
var dataURL = canvas.toDataURL("image/jpeg");
callback(dataURL);
canvas = null;
}
for(var i = 0; i < myimgarray.length; i++)
{
icount.count = i;
var img = new Image();
alert(checkoutimgarray);
img.src = '/Portals/0/repair-images/' + myimgarray[i];
img.onload = function(){
newData = convertImgToBase64(img);
alert(newData);
doc.addImage(newData, 'JPEG', (icount * 100), 10, 70, 15); // would doc be undefined here? out of scope?
};
}
doc.setFontSize(20);
doc.text(100, 20, "This is a test to see if images will show");
doc.save('My_file.pdf');
});
});
var canvas = document.createElement("canvas");
var ctx = canvas.getContext("2d");
function convertImgToBase64(img, outputFormat){
// clear canvas
canvas.width = img.width;
canvas.height = img.height;
// draw image
ctx.drawImage(img, 0, 0);
// get data url of output format or defaults to jpeg if not set
return canvas.toDataURL("image/" + (outputFormat || "jpeg"));
}
var images = [];
for(var i = 0; i < myimgarray.length; i++) {
var img = new Image();
img.onload = function() {
images.push({
base64: convertImgToBase64(this),
width: this.width,
height: this.height
});
// all images loaded
if(images.length === myimgarray.length) {
for(var j = 0; j < images.length; j++) {
doc.addImage(images[j].base64, 'JPEG', (j * 100), 10, 70, 15);
}
doc.setFontSize(20);
doc.text(100, 20, "This is a test to see if images will show");
doc.save('My_file.pdf');
}
};
img.src = '/Portals/0/repair-images/' + myimgarray[i];
}

load image inside JavaScript function

i have function to get image pixels color
function getImage(imgsrc){
var img = $( "<img>", {
src: imgsrc
});
var imageMap = new Object();
img.load(function() {
var canvas = $('<canvas/>')[0].getContext('2d');
canvas.width = this.width;
canvas.height = this.height;
canvas.drawImage(this, 0, 0, this.width, this.height);
for(var i = 0;i < this.width;i++){
imageMap[i] = new Object();
for(var j = 0;j < this.width;j++){
var pixelData = canvas.getImageData(i, j, 1, 1).data;
imageMap[i][j] = rgbToHex(pixelData[0],pixelData[1],pixelData[2]);
}
}
console.log(imageMap[40][40]);
});
console.log(imageMap[40][40]);
return imageMap;
}
but it return undefined(it print 2nd console.log first)
what's wrong?
thx.
Your function is returning undefined because load is asynchronous. getImage is trying to return something before load finished loading.
You'll need to pass a callback to execute when the image has loaded, to getImage:
function getImage(imgsrc, callback){
var img = $( "<img>", {
src: imgsrc
});
var imageMap = new Object();
img.load(function() {
var canvas = $('<canvas/>')[0].getContext('2d');
canvas.width = this.width;
canvas.height = this.height;
canvas.drawImage(this, 0, 0, this.width, this.height);
for(var i = 0;i < this.width;i++){
imageMap[i] = new Object();
for(var j = 0;j < this.width;j++){
var pixelData = canvas.getImageData(i, j, 1, 1).data;
imageMap[i][j] = rgbToHex(pixelData[0],pixelData[1],pixelData[2]);
}
}
console.log(imageMap[40][40]);
callback(imageMap)
});
}
Then you just call the function like this:
getImage("http://some.src.jpg", function(imageMap){
// Do stuff with imageMap here;
});
Of course, you can also define the callback elsewhere:
var myCallback = function(imageMap){
// Do stuff with imageMap here;
};
getImage("http://some.src.jpg", myCallback);
Now that promises starts to get [have] wide support you can do this instead:
// Define a common load function:
function loadImage(url) {
return new Promise(function(resolve, reject) {
var img = new Image;
img.onload = function() { resolve(this) };
img.onerror = img.onabort = function() { reject("Error loading image") };
img.src = url;
})
}
// Usage:
loadImage("https://i.stack.imgur.com/ynBVu.gif").then(function(image) {
// Use the `image` here
document.body.appendChild(image);
})
The promise will take the callback, states etc. internally. IE will get support in next version (there exists polyfill for it).
jQuery.load() is asynchronous, meaning the code will continue while it goes of working away.
If you want to process the imagemap, one option could be to pass a callback you execute ones the imagemap is populated, similar to:
function yourCallback(imageMap){
// ...process imageMap;
}
function getImage(imgsrc, yourCallback) {
var img = $("<img>", {
src: imgsrc
});
var imageMap = new Object();
img.load(function () {
var canvas = $('<canvas/>')[0].getContext('2d');
canvas.width = this.width;
canvas.height = this.height;
canvas.drawImage(this, 0, 0, this.width, this.height);
for (var i = 0; i < this.width; i++) {
imageMap[i] = new Object();
for (var j = 0; j < this.width; j++) {
var pixelData = canvas.getImageData(i, j, 1, 1).data;
imageMap[i][j] = rgbToHex(pixelData[0], pixelData[1], pixelData[2]);
}
}
yourCallback(imageMap);
});
}
getImage(imgsrc,yourCallback);

Categories