'Resize image before saving with Node.js
I have an upload function like this :
app.post("/upload", function (req, res) {
let base64 = req.body.image.replace(/^data:image\/png;base64,/, "");
binaryData = Buffer.from(base64, "base64").toString("binary");
fs.writeFile(
"./pictures/" + Date.now() + ".png",
binaryData,
"binary",
function (err) {
if (err) {
console.log(err);
}
}
);
fs.writeFile(
"./thumbnails/" + Date.now() + ".png",
binaryData,
"binary",
function (err) {
if (err) {
console.log(err);
}
}
);
The first part saves image into "pictures" folder. That works ok, nothing to do here.
The second parts saves the same image into "thumbnails" folder. What I need to do is to resize the image before its saved, to have only resized images in that folder.
Solution 1:[1]
You can try with Sharp library: https://sharp.pixelplumbing.com/api-resize
app.post("/upload", function (req, res) {
let base64 = req.body.image.replace(/^data:image\/png;base64,/, "");
binaryData = Buffer.from(base64, "base64").toString("binary");
fs.writeFile(
"./pictures/" + Date.now() + ".png",
binaryData,
"binary",
function (err) {
if (err) {
console.log(err);
}
}
);
sharp(binaryData)
.resize({ width: 100 })
.toBuffer()
.then(data => {
// 100 pixels wide, auto-scaled height
fs.writeFile(
"./thumbnails/" + Date.now() + ".png",
data,
"binary",
function (err) {
if (err) {
console.log(err);
}
}
)
})
})
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Guille Sanchez |
