如何使用Multer在NodeJS中使用锐化来减小图像大小?

tpxzln5u  于 2023-05-17  发布在  Node.js
关注(0)|答案(2)|浏览(149)

请有人帮助我如何在NodeJS中使用Multer缩小图像大小,并通过示例向我展示?
我试过与穆特和没有工作。

bvjveswy

bvjveswy1#

app.post("/upload", upload.single("image"), async (req, res) => {
        const image = await sharp(req.file.buffer);
        const resizedImage = image.resize({ width: 500, height: 500 });
        await resizedImage.toFile("uploads/resized-" + req.file.originalname);
        res.sendFile("uploads/resized-" + req.file.originalname);
    })
uujelgoq

uujelgoq2#

下面是一个基本的Node.js服务器,它使用Multer和Sharp来调整上传图像的大小:

const express = require('express');
const multer = require('multer');
const sharp = require('sharp');

const app = express();

// Multer configuration
const upload = multer({
    limits: {
        fileSize: 4 * 1024 * 1024,
    }
});

app.post('/upload', upload.single('image'), async (req, res) => {
    try {
        const buffer = await sharp(req.file.buffer)
            .resize({ width: 500, height: 500 })
            .png()
            .toBuffer();

        // You can now write the buffer to a file, or save it to a database,
        // or send it over the network, etc.

        res.send('Image uploaded and resized');
    } catch (err) {
        res.status(400).send({ error: err.message });
    }
});

app.listen(3000, () => {
    console.log('Server is up on port 3000');
});

相关问题