上传图像后,我可以使用imagemin-webp压缩图像吗?

时间:2019-10-26 20:54:06

标签: node.js multer imagemin

我想压缩png和jpg图像并将其转换为webp格式。我找到了imagemin-webp库,我想使用它,但是我发现了这个示例,该示例从一个目录中提取文件,然后将它们发布到另一个目录中:

const imagemin = require('imagemin');
const imageminWebp = require('imagemin-webp');

imagemin(['images/*.{jpg,png}'], 'build/images', {
    use: [
        imageminWebp({quality: 50})
    ]
}).then(() => {
    console.log('Images optimized');
});

我要做的是在用户上传一些图片时使用此技术,因此multer会获取图片,然后imagemin压缩它们并将其存储。 这是我的带有上载代码的图片上传API

let storage = multer.diskStorage({
    destination: function (req, file, cb) {
        cb(null, './uploads/rooms');
    },
    filename: function (req, file, cb) {
        cb(null, req.params.room_id + "_" + Date.now() + "_" + Math.floor(Math.random() * 10000) + file.originalname.substr(-7));
    }
});
let upload = multer({ storage: storage })

//add pictures to a room
venuesRoutes.route('/:id/room/:room_id/add_pictures').post(upload.array('pics', 20), function (req, res) {

    Venue.findOne({ _id: req.params.id, user: req.user._id }).populate('city').populate('rooms.availability').exec(function (err, venue) {
        if (err) {
            res.status(404).send("venue is not found");
        }
        else {
            let room = venue.rooms.id(req.params.room_id)

            req.files.map((pic) => {

                room.pics.push({ path: pic.path })
            })
            venue.save(function (err) {
                if (!err) res.status(200).send({ msg: "pictures updated", venue: venue });
            });
        }
    });
});

0 个答案:

没有答案