I try to implement multi crop with raw. cause, traditional ways extract then save to buffer is to slow . for my task, an image it takes 700ms. i want to cutdown extract call with manipulate raw data. so it can speed up 10x - 20x. my problem in extract frame into sequential block size. lets say 16x16 from left top to right bottom.
const sharp = require('sharp');
const benchmark = () => {
return new Promise((resolve) => {
const currentTime = Date.now();
resolve(currentTime)
})
};
const encode = async (absolutePathFile) => {
const start_time = await benchmark();
const image = await sharp(absolutePathFile);
const { data, info } = await image.ensureAlpha(1).raw().toBuffer({ resolveWithObject: true });
const { width, height, channels } = info;
const colors = new Uint8ClampedArray(data.buffer);
const pixels = [];
const frame = [];
const frameBlocks = [];
// Convert colors to RGBA pixel
for (let i=0; i < colors.length; i += channels) {
const pixel = [];
for (let j=i; j < i + channels; j++) {
pixel.push(colors[j])
};
pixels.push(pixel)
}
// Convert pixels to frame
let index = 0;
for (let i=0; i < width; i++) {
frame[i] = [];
for (let j=0; j < height; j++) {
frame[i][j] = pixels[index];
index += 1;
}
};
// Crop frame to piece of block size from left top to right bottom.
const wBlockSize = 16;
const hBlockSize = 16;
const wBlockLength = Math.floor(width/wBlockSize);
const hBlockLength = Math.floor(height/hBlockSize);
for (let i=0; i < wBlockLength; i++) {
for (let j=0; j < hBlockLength; j++) {
const block = [];
for (let k=i; k < i+wBlockSize; k++) {
for (let l=j; l+hBlockSize; l++) {
block.push(frame[k][l])
}
};
frameBlocks.push(block)
}
};
const end_time = await benchmark();
const finish_time = end_time - start_time;
console.log(finish_time);
console.log(frameBlocks.length)
};
encode(`${__dirname}/public/image.jpg`)