I am actually trying to resize image using sharp
package. For Reference: https://www.npmjs.com/package/sharp
I am getting image data from frontend (which is in react) to Backend (Which is in node) as below
imageData {
name: 'xyz.JPEG',
data: <Buffer ff d8 ff e0 00 10 4a 46 49 46 00 01 01 00 00 01 00 01 00 00 ff db 00 43 00 01 01 01 01 01 01 01 01 01 01 01 01
01 01 01 01 01 01 01 01 01 01 01 01 01 ... 23589 more bytes>,
size: 23639,
encoding: '7bit',
tempFilePath: '',
truncated: false,
mimetype: 'image/jpeg',
md5: '899917d14fe775aa2097487e3ddcc9f6',
mv: [Function: mv]
}
But I am not understanding which function to use exactly for the format which I am getting to the backend. As I am not understanding exactly where the buffer output is being passed in the sharp package functions.
Please help me out. Thanks
I've added an example below of scaling the image data by a constant factor, for example, 0.25. This will scale both width and height for the image.
There are more useful examples in the docs: https://sharp.pixelplumbing.com/api-resize#resize
const sharp = require("sharp");
// Resize both width and height to max dimension.
async function resizeImageBuffer(imageBuffer, maxDimension) {
const sharpImg = await sharp(imageBuffer);
return sharpImg.resize({ width: maxDimension, height: maxDimension, fit: 'contain', background: { r: 255, g: 255, b: 255, alpha: 1 } }).toBuffer();
}
async function testResize(imgData) {
console.log(`testResize: Resizing: ${imgData.name}...`);
const MAX_DIMENSION = 64;
let resized = await resizeImageBuffer(imgData.data, MAX_DIMENSION);
console.log(`testResize: resize complete: original: ${imgData.data.length} bytes, resized: ${resized.length} bytes.`);
fs.writeFileSync(path.join(outputDir, imgData.name), resized);
}
testResize(imgData);