Overview
Images are natively supported in HTML and the browser. However, images can be processed and manipulated with Javascript. This requires an api for retrieving the and econding the image in a data structure that Javascript can manipulate.
Image Encoding
Javascript provides a method to read and manipulate the pixels Every pixel is encoded by four pieces of information.
- Red - value between 0-255
- Green - value between 0-255
- Blue - value between 0-255
- Alpha - value between 0-255. 0 is transparent and 255 is visible
The following code retrieves a Javascript array of values of pixels from an image in an HTML page contained in an HTML canvas.
const canvas = document.getElementById("myCanvas");
const context = canvas.getContext("2d");
let imgData = context.getImageData(img.imageX, img.imageY, img.imageWidth, img.imageHeight);
let data = imgData.data;
for (let i = 0, n = data.length; i < n; i += 4) {
let red = data[i];
let green = data[i + 1];
let blue = data[i + 2];
let alpha = data[i + 3];
}
{% img.imageHeight %} and {% img.imageWidth %} are given in numbers of pixels. The imageData is encoded as an array. Its size is
{% size = imageHeight \times imageWidth \times 4 %}
The first {% imageWidth \times 4 %} items in the array, represent the first row of pixels in the image.
Image Pixels Arranged as Matrices
The image pixel array can be reshaped into a set of four rectangular matrices, using the image library.
let ig = await import('/lib/image/v1.0.0/image.mjs');
let matrices = ig.matrices(data,img.imageWidth);
let redMatrix = matrices.red;
let greenMatrix = matrices.green;
let blueMatrix = matrices.blue;
let alphaMatrix = matrices.alpha;
//recover the initial flat array
let data = ig.flatten(redMatrix, greendMatrix, blueMatrix, alphaMatrix);