What you need is data
in your imageData
from the frontend and use resize
function in sharp
module.
Here's an example on how to resize the image to 150 pixels in width:
import sharp from 'sharp';
/*
* This function will return a Promise<Buffer>
*/
async function resize(imageData) {
return sharp(imageData.data).resize(150).toBuffer();
}
Here's the documentation for resize
method (v0.27.2):
/**
* Resize image to width, height or width x height.
*
* When both a width and height are provided, the possible methods by which the image should fit these are:
* - cover: Crop to cover both provided dimensions (the default).
* - contain: Embed within both provided dimensions.
* - fill: Ignore the aspect ratio of the input and stretch to both provided dimensions.
* - inside: Preserving aspect ratio, resize the image to be as large as possible while ensuring its dimensions are less than or equal to both those specified.
* - outside: Preserving aspect ratio, resize the image to be as small as possible while ensuring its dimensions are greater than or equal to both those specified.
* Some of these values are based on the object-fit CSS property.
*
* When using a fit of cover or contain, the default position is centre. Other options are:
* - sharp.position: top, right top, right, right bottom, bottom, left bottom, left, left top.
* - sharp.gravity: north, northeast, east, southeast, south, southwest, west, northwest, center or centre.
* - sharp.strategy: cover only, dynamically crop using either the entropy or attention strategy. Some of these values are based on the object-position CSS property.
*
* The experimental strategy-based approach resizes so one dimension is at its target length then repeatedly ranks edge regions,
* discarding the edge with the lowest score based on the selected strategy.
* - entropy: focus on the region with the highest Shannon entropy.
* - attention: focus on the region with the highest luminance frequency, colour saturation and presence of skin tones.
*
* Possible interpolation kernels are:
* - nearest: Use nearest neighbour interpolation.
* - cubic: Use a Catmull-Rom spline.
* - lanczos2: Use a Lanczos kernel with a=2.
* - lanczos3: Use a Lanczos kernel with a=3 (the default).
*
* @param width pixels wide the resultant image should be. Use null or undefined to auto-scale the width to match the height.
* @param height pixels high the resultant image should be. Use null or undefined to auto-scale the height to match the width.
* @param options resize options
* @throws {Error} Invalid parameters
* @returns A sharp instance that can be used to chain operations
*/
resize(width?: number | null, height?: number | null, options?: ResizeOptions): Sharp;