如何在Node JS Public / uploads / image中获得具有质量百分比的图像

时间:2019-06-14 09:27:43

标签: node.js image express image-processing

1 个答案:

答案 0 :(得分:1)

如果您希望转换质量水平,建议您尝试Jimp。这使我们能够轻松转换Jpeg图像质量。

const express = require('express');
const app = express();
const port = 3000;
const Jimp = require('jimp');

function getImage(imageFile, qualityPercent) {
    return Jimp.read(imageFile)
    .then(image => {
        // Convert to new quality level %
        return image.quality(qualityPercent).getBufferAsync(Jimp.MIME_JPEG);
    });
}

app.get('/images/:imageFileName', async (req, res) => {
    let imageFileName = req.params.imageFileName;

    // Get the quality requested in percent, e.g. /images/original_image.jpeg?quality=15
    let qualityPercent = Number(req.query.quality) || 100;
    let imageBuffer = await getImage(imageFileName, qualityPercent);
    res.writeHead(200, {
        'Content-Type': 'image/jpg',
        'Content-Length': imageBuffer.length
    });

    console.log(`Serving ${imageFileName} at ${qualityPercent}% quality...`);
    res.end(imageBuffer);
});

app.listen(port);

运行此服务器,您可以请求带有url的图像(例如):

http://localhost:3000/images/original_image.jpeg?quality=25