Image to Uint8Array in Javascript [duplicate] - javascript

This question already has answers here:
convert image src data: into Uint8Array
(1 answer)
Get image data URL in JavaScript?
(9 answers)
Closed 1 year ago.
I have a image that needs to converted to Uint8Array.
For Example:
var image = new Image();
image.src="image13.jpg";
Now i need to transform this image variable to Uint8Array. Is there any function in JS, which allows to achieve this functionality?

You may use the Canvas API to retrieve the image data:
Retrieving the data in the binary form of various image formats (PNG, JPEG, etc.) using canvas.toBlob() and blob.arrayBuffer():
async function imageToUint8Array(image, context) {
context.width = image.width;
context.height = image.height;
context.drawImage(image, 0, 0);
const blob = await context.canvas.toBlob(
callback,
"image/jpeg" // the MIME type of the image format
1 // quality (in the range 0..1)
);
return new Uint8Array(await blob.arrayBuffer());
}
function toBlob(canvas, type = "image/png", quality = 1) {
return new Promise((resolve) => canvas.toBlob(blob => resolve(blob)))
}
async function imageToUint8Array(image, context) {
context.width = image.width;
context.height = image.height;
context.drawImage(image, 0, 0);
const blob = await toBlob(context.canvas, "image/png");
return new Uint8Array(await blob.arrayBuffer());
}
const image = new Image();
// stackoverflow logo
image.src = `data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAOEAAADhCAMAAAAJbSJIAAAAe1BMVEX///8AAABMTEyamppvb29VVVW2trbi4uI1NTXExMQ6Ojo+Pj729vbr6+v6+vrZ2dlFRUWnp6dhYWGIiIjPz899fX3p6ekyMjK8vLyTk5Otra2fn59JSUnAwMAlJSWkpKQRERErKytcXFyEhIQODg4bGxtra2t5eXkfHx84s96BAAAFyElEQVR4nO2ba3eqOhRFRa1WRVHAB6DWR2vP//+Ft2KBbNgBrRIS7prfjknP2HMY81iETgcAAAAAAAAAAAAAAAAAAAAAAAAAAAAAgAJWo8gdNl1ETdj+4ntiXdk0XUotDKyMoOliasEXDN2mi6kFWzD8bLqYehAMrVnTxdTCm2DoNF1MLXiC4aDpYmpBnEy9poupBUcwfGu6mFqYiVNN08U8g3yaPAiGtsKKXkwkL94VDH2VNb2S6aTkNxYIhguVVb2QMK4+l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cWXZ8tVeEHkgdsBdgXZ8xgNjofqgWNjp5+mIaFU0QeLeebdPdy1706J+qWGcZ9QvrPxkmfad59Ddv3mPsZMd24PUtTayv6IR43/MHesOvI7aZNKwyvDMPC9vy2T22N4RWnR7Z3tw9bZdiJ15Hkdubl9okBhg9vpKeD+H/5jUkNMNxb1vj0HSw2/vB+2eHH5PcgZYAhnT4m7jIId87q7qOtcYYZh7m77IWjKln9DW1Wj/Jvezn3BiOHu6Oov6E0SeTZd/teJMrqb3h3SJMjeeKkv6HkKmIlSb6ov6HkykwlSbaov6Hk0W4lyQ9Rf8NH4ieR5O/1N5RcJW2R4bl7/ItgmkLpbxgzdUaDyOt3+cuIHN3kTw0xzJj9yIa982XLXkrISC8hGmcoMFtdZZfunEsW0yTRZEMBe+XswmDpZllx+jpUSwwF7KG/WQT99JFp+wzzwFA1/0NDfz3hGae851mv1wdzzoe5t7PuBoaNAUMYwrB5YAhDGDZPwVDyLkyLDJ8GhqqB4ePAUDUwfBwYqub1hhtdDddR7yVEfV0Na6BptxswhCEMmweG5htWviVivKG37daFIe88AwAAAAAAAAAAAAAAAAAAAAAAAAAAAIB6/gNRC0RU8255zwAAAABJRU5ErkJggg==`;
const canvas = document.createElement("canvas");
const context = canvas.getContext("2d");
image.onload = async() => console.log(await imageToUint8Array(image, context));
Retrieving the raw image pixels using canvas.getImageData():
function imageToUint8Array(image, context) {
context.width = image.width;
context.height = image.height;
context.drawImage(image, 0, 0);
// `getImageData().data` is a `Uint8ClampedArray`, which differs from `Uint8Array` only in
// how data is treated when values are being *set*, so it is valid to perform the conversion
// into a `Uint8Array`.
return new Uint8Array(context.getImageData(0, 0, image.width, image.height).data.buffer);
}
function imageToUint8Array(image, context) {
context.width = image.width;
context.height = image.height;
context.drawImage(image, 0, 0);
// `getImageData().data` is a `Uint8ClampedArray`, which differs from `Uint8Array` only in
// how data is treated when values are being *set*, so it is valid to perform the conversion
// into a `Uint8Array`.
return new Uint8Array(context.getImageData(0, 0, image.width, image.height).data.buffer);
}
const image = new Image();
// stackoverflow logo
image.src = `data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAOEAAADhCAMAAAAJbSJIAAAAe1BMVEX///8AAABMTEyamppvb29VVVW2trbi4uI1NTXExMQ6Ojo+Pj729vbr6+v6+vrZ2dlFRUWnp6dhYWGIiIjPz899fX3p6ekyMjK8vLyTk5Otra2fn59JSUnAwMAlJSWkpKQRERErKytcXFyEhIQODg4bGxtra2t5eXkfHx84s96BAAAFyElEQVR4nO2ba3eqOhRFRa1WRVHAB6DWR2vP//+Ft2KBbNgBrRIS7prfjknP2HMY81iETgcAAAAAAAAAAAAAAAAAAAAAAAAAAAAAgAJWo8gdNl1ETdj+4ntiXdk0XUotDKyMoOliasEXDN2mi6kFWzD8bLqYehAMrVnTxdTCm2DoNF1MLXiC4aDpYmpBnEy9poupBUcwfGu6mFqYiVNN08U8g3yaPAiGtsKKXkwkL94VDH2VNb2S6aTkNxYIhguVVb2QMK4+lLTuBMOl0rpehd39LX/Ktw8Fw7na0l7DprJ8syfT2Uko/4Pvsxa6SL5njbEIfP19ocdIcX3P80EM39k+kdAjUlzfC5gTxR7XZSR06Kuu73lsYmhxYdNUaF8rL/B5QmK457qYPZnSIy5/QBJHsomJYm6cMuf4pdBsZKK4IYaHYoeF0GxmougSxeLe0/xEkRxymSOSOI4P6st7BSOqWGgXGw1NFPvEsLCstyFRpF9ifvfZhkTRp4q5odiKRHFJDHMzZjsSxQNRpAt7OxJFhxjmordPaYtJeMSQDsZWJIqdzpEokugtkDVoRsX4GhJDEmmIW1eNE0W7aqbvEUMxejMkUXQLc2SeMVEUozcjJtPboj4vO8JOiaG1ylrE36i2ieK/5HdUsndeEEMhlDEhURRyw5LZcEsUs+OuAYkiySrW0gOCLHozIFGk5yOrL1s5BqRbGr2t+MGrEbk9WclYk0Rv4oeKan6MtVXgi99+5SKNZDxPuLGrEfTxRMKJnfd3pE9y00s8Xe0UVn4vNj3+pbDZIBu96Z8oDicWC/d90B63wWxCok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EfV0Na6BptxswhCEMmweG5htWviVivKG37daFIe88AwAAAAAAAAAAAAAAAAAAAAAAAAAAAIB6/gNRC0RU8255zwAAAABJRU5ErkJggg==`;
const canvas = document.createElement("canvas");
const context = canvas.getContext("2d");
image.onload = async() => console.log(imageToUint8Array(image, context));

Related

How to convert base64 to RGBA8888

I'm trying to convert and image to base 64 and then to RGBA8888 to feed camera buffer, I'm stuck when trying to convert from base64 to rgba.
function encodeImageFileAsURL(element) {
var file = element.files[0];
var reader = new FileReader();
reader.onloadend = function() {
console.log('RESULT', reader.result)
}
reader.readAsDataURL(file);
}
<input type="file" onchange="encodeImageFileAsURL(this)" />
Canvas - I use canvas because it has ways to get at the underlying data, and ways to render any kind of image format onto itself.
Html image tag - not sure if this was necessary, but it provides an easy way to draw an image file onto a canvas.
I take the file from your reader code, insert it into an img, render that img onto a canvas, and then extract the raw RGBA frame from the canvas. You can find out about the data format here (data property). I hope that is a suitable format for your application.
const canvas = document.createElement("canvas");
const ctx = canvas.getContext('2d');
function encodeImageFileAsURL(element) {
var file = element.files[0];
var reader = new FileReader();
reader.onloadend = function() {
const img = document.createElement("img");
img.onload = () => {
const w = img.naturalWidth, h = img.naturalHeight;
ctx.drawImage(img, 0, 0);
const imgData = ctx.getImageData(0, 0, w, h);
const arr = Uint8ClampedArray.from(imgData.data);
// do something with arr
console.log(`image width: ${w}, image height: ${h}, expected raw data size (w x h x 4): ${w * h * 4}, actual size: ${arr.length}`);
};
img.src = reader.result;
};
reader.readAsDataURL(file);
}
<input type="file" onchange="encodeImageFileAsURL(this)" />

problems with image resizing

I'm trying to resize an image which comes from a Quill editor.
I used this links as guides:
https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/drawImage
Resize image with javascript canvas (smoothly)
This is my code:
async handleImageAdded(file, Editor, cursorLocation, resetUploader) {
// Resizing
var img = document.createElement("img");
img.src = URL.createObjectURL(file);
var canvas = document.createElement("canvas");
var ctx = canvas.getContext("2d");
ctx.drawImage(img, 0, 0, 200, 200);
var newFile = await new Promise(resolve => canvas.toBlob(resolve));
document.getElementById("preview").src = URL.createObjectURL(newFile); //check
//Sending data to server
Expected behaviour: will display a resized version of the image which was sent in a file variable. (if I switch newFile to file, everything works just as expected)
Current behaviour: a white rectangle 300x150px
Could you please help me to find what am I missing?
The reason was the absence of image.onload event handler.
This worked for me:
async handleImageAdded(file, Editor, cursorLocation, resetUploader) {
// Resizing
var img = document.createElement("img");
img.src = URL.createObjectURL(file);
var newFile;
const promise = new Promise(resolve => {
img.onload = function (event) {
// Dynamically create a canvas element
var canvas = document.createElement("canvas");
// var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
// Actual resizing
ctx.drawImage(img, 0, 0, img.width * 0.5, img.height * 0.5);
canvas.toBlob(blob => {
newFile = blob;
console.log(newFile)
resolve();
});
// Show resized image in preview element
//var dataurl = canvas.toDataURL(file.type);
//document.getElementById("preview").src = dataurl;
}
})
await promise;
//var newFile = await new Promise(resolve => canvas.toBlob(resolve));
document.getElementById("preview").src = URL.createObjectURL(newFile); //check

jpg loaded with python keras is different from jpg loaded in javascript

I am loading jpg image in python on the server. Then I am loading the same jpg image with javascript on the client. Finally, I am trying to compare it with the python output. But loaded data are different so images do not match. Where do I have a mistake?
Python code
from keras.preprocessing.image import load_img
from keras.preprocessing.image import img_to_array
filename = './rcl.jpg'
original = load_img(filename)
numpy_image = img_to_array(original)
print(numpy_image)
JS code
import * as tf from '#tensorflow/tfjs';
photo() {
var can = document.createElement('canvas');
var ctx = can.getContext("2d");
var img = new Image();
img.onload = function() {
ctx.drawImage(img, 0, 0);
};
img.crossOrigin = "anonymous";
img.src = './rcl.jpg';
var tensor = tf.fromPixels(can).toFloat();
tensor.print()
}
You are drawing the image on a canvas before rendering the canvas as a tensor. Drawing on a canvas can alter the shape of the initial image. For instance, unless specified otherwise - which is the case with your code - the canvas is created with a width of 300 px and a height of 150 px. Therefore the resulting shape of the tensor will be more or less something like the following [150, 300, 3].
1- Using Canvas
Canvas are suited to resize an image as one can draw on the canvas all or part of the initial image. In that case, one needs to resize the canvas.
const canvas = document.create('canvas')
// canvas has initial width: 300px and height: 150px
canvas.width = image.width
canvas.height = image.heigth
// canvas is set to redraw the initial image
const ctx = canvas.getContext('2d')
ctx.drawImage(image, 0, 0) // to draw the entire image
One word of caution though: all the above piece should be executed after the image has finished loading using the event handler onload as the following
const im = new Image()
im.crossOrigin = 'anonymous'
im.src = 'url'
// document.body.appendChild(im) (optional if the image should be displayed)
im.onload = () => {
const canvas = document.create('canvas')
canvas.width = image.width
canvas.height = image.heigth
const ctx = canvas.getContext('2d')
ctx.drawImage(image, 0, 0)
}
or using async/await
function load(url){
return new Promise((resolve, reject) => {
const im = new Image()
im.crossOrigin = 'anonymous'
im.src = 'url'
im.onload = () => {
resolve(im)
}
})
}
// use the load function inside an async function
(async() => {
const image = await load(url)
const canvas = document.create('canvas')
canvas.width = image.width
canvas.height = image.heigth
const ctx = canvas.getContext('2d')
ctx.drawImage(image, 0, 0)
})()
2- Using fromPixel on the image directly
If the image is not to be resized, you can directly render the image as a tensor using fromPixel on the image itself

Can't redraw image represented in base64

First part of my application loads picture with file chooser from my file system and draws image to canvas. I take that canvas and convert it to data URL and also save it in my database.
var imgData = canvas.toDataURL("image/jpg");
factory.saveData(imgData); // execute some java code
Here is the problem. I can't redraw that image, my javascript:
var pic = new Image();
pic.onload = function() {
ctx.drawImage(pic, 0, 0); // ctx = canvas.getContext("2d")
};
// This data url is copy/pasted from database for simplicity
pic.src = "data:image/png;base64,iVBOR..........ElFTkSuQmCC";
Onload function is called but I just get transparent image.
Probably has something to do with the fact that getDataFromDatabase() is asynchronous so you're returning a promise object to pic.src instead of the data url. Fix this by using a then call on getDataFromDatabase and using the result on pic.src like this:
var pic = new Image();
var pic.onload = function() {
ctx.drawImage(pic, 0, 0);
};
getDataFromDatabase().then(dataUrl => {
pic.src = dataUrl;
});
Here's a full example of this in action. I draw to a canvas, store the canvas data as a base64 data url into a variable, save it into a mock DB using closures, then reload the data from a simulated asynchronous function call by using a promise.
const canvas = document.getElementById('myCanvas');
const ctx = canvas.getContext('2d');
// Initialize canvas to a random image
const imageUrl = 'https://cdn.sstatic.net/Sites/stackoverflow/company/img/logos/so/so-logo.svg?v=a010291124bf';
const initialImage = new Image();
initialImage.src = imageUrl;
initialImage.onload = function() {
ctx.drawImage(initialImage, 0, 0);
}
// Convert canvas to base64 data url
const imageData = canvas.toDataURL('image/png');
const getDataFromDatabase = saveData(imageData);
// Clear the canvas
ctx.clearRect(0, 0, canvas.width, canvas.height);
// Redraw the image
const pic = new Image();
getDataFromDatabase().then(data => {
pic.src = data;
});
pic.onload = function() {
ctx.drawImage(pic, 0, 0);
}
function saveData(image) {
return function getDataFromDatabase() {
return new Promise(resolve => {
resolve(image);
});
}
}
<canvas id="myCanvas">
</canvas>
Edit: It shouldn't really matter where you get the image data from. If the data is not malformed, it should draw to the canvas. Here's an example identical to the way you're loading image data (from a hardcoded data url):
const imageData = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAOEAAADhCAMAAAAJbSJIAAAAwFBMVEX/pQD/////owD/oQD/pgD/9+r/u0P//fj/2I////z/+/H/qQ//2KD/u07/2pz/9+j/vlj/0X3/0Iz/rAD/5Lv/3p//7Mj/9OD/8Nb/68v/367/897/9uj/58H/7tL/sTD/1pX/xWz/xWL/tDf/3Kf/zX7/rx//ynb/sjr/3Kz/uEj/ty7/syH/wF7/4bb/rif/wFD/48D/vD//y4T/xXX/1Zr/xFj/0oP/t1H/xXv/y4X/qh//3rT/zXD/wGj/vkikmGS4AAARK0lEQVR4nNWdeWOiPBPAYYIiULUVq3jjbT27PffdPt1+/2/1Al6JBCQxAXb+tAr5NclkjmSiqLLFMHRdN/vtx9JeKo+Tdq/fNHVfDEP6+xWJzzbMbrM/+RwV1xoKC1j26nlYa/ebXVOX2ApZhGan/+tp+mMHLAAKRbyPwf+zXRy+/2o5BUktkULY7D29lmeaz0ZDC5F6X7SLb091x5TQGOGEemvyZzPQksERmDArv7n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8ga9RNXf4kXQYS+NL4HlxcDcNGBtdu0BeGpQglVtdCe/97dAunhzZZJK54nFKGEnlTbtb/jiFtJrtEhbbD5MxGKp4on9KTQeHrf7JTwhR1xcAhmm9pTj6tWWLxIIFT3F8y8D1/sq7f7QVCgxx6P3F/9pgjNGRY5hL7oZrfpTObFtRZziMRa/8wnTrNakEPnizzCvRi6rpv9dukhJJ+lrWN6fxWnNenyfz1KPpfipf7sAAAAAElFTkSuQmCC';
const canvas = document.getElementById('myCanvas');
const ctx = canvas.getContext('2d');
const image = new Image();
image.onload = function() {
ctx.drawImage(image, 0, 0);
}
image.src = imageData;
<canvas id="myCanvas">
</canvas>
I suggest you check your image data using a base64 image decoder to see if your image data is malformed or not. If your data url is valid, then something else I can suggest is ensuring your canvas width and height are equal to or greater than the image's width and height or else it'll be hidden (if the image you're supplying has empty space / padding).

Convert an image to ImageData (Uint8ClampedArray)

I have an image for example
"img/Myimage.jpg"
I would like to convert it to the Uint8ClampedArray format (as shown in the image).
For what? I am using a library that after a long process converts the images to this format, but I have others images that I need to convert them on my own to this same format. how can I do it? Excuse my ignorance
var frames = animator.frames;
var res_c = document.getElementById("result");
var res_ctx = res_c.getContext('2d');
for (var x = 0; x < frames.length; x++) {
//***frames are ImageData (Uint8ClampedArray)***
res_ctx.putImageData(frames[x],0,0);
console.log(frames[x])
gif.addFrame(res_c,{copy:true,delay: 120});
}
I need convert my images in ImageData (Uint8ClampedArray) for add others frames
You can use Image constructor, CanvasRenderingContext2D.drawImage() and CanvasRenderingContext2D.getImageData() to create an ImageData object from an image file.
const canvas = document.querySelector("canvas");
const ctx = canvas.getContext("2d");
const width = 300;
const height = 311;
const image = new Image;
image.src = /* Blob URL, "/path/to/image/served/with/cors/headers" */;
image.onload = () => {
ctx.drawImage(image, 0, 0);
imageData = ctx.getImageData(0, 0, 300, 311);
console.log(imageData);
}
An async/await solution using the canvas draw-extract method, takes one paramter as a source string (can pass image.src if you already have an image):
/** #param {string} source */
async function imageDataFromSource (source) {
const image = Object.assign(new Image(), { src: source });
await new Promise(resolve => image.addEventListener('load', () => resolve()));
const context = Object.assign(document.createElement('canvas'), {
width: image.width,
height: image.height
}).getContext('2d');
context.imageSmoothingEnabled = false;
context.drawImage(image, 0, 0);
return context.getImageData(0, 0, image.width, image.height);
}
Example:
// image source
const source = 'https://raw.githubusercontent.com/Rovoska/undertale/master/sprites/images/spr_maincharad_3.png';
// async wrapper
async epic () {
// log data to console
console.log(await imageDataFromSource(source));
}
// do the epic
epic();

Categories

Resources