簡體   English   中英

如何使用sharp.js將圖像從緩沖區存儲到node.js中的文件系統

[英]how to store image from buffer to file system in node.js using sharp.js

我在 node.js 中使用sharp.js 進行圖像處理

我的代碼

sharp(path)
        .toFormat('jpeg')
        .toBuffer((err, data, info) => {
            fs.writeFile(temp, buffer, { flag: 'w' }, function() {
                response.sendFile(temp);
            });
        });

這里 fs 中的 temp 表示“路徑” var temp= imageDir + request.params.id; ( http://localhost:2000/images/we.png )

  1. 將圖像上傳為 png 格式或任何其他格式

  2. 使用.toFormat('jpeg')將該圖像轉換為JPEG並發送到緩沖區

  3. 想要將該圖像從緩沖區保存到

您的代碼沒有“緩沖區”。 你應該寫數據。

.toBuffer((err, data, info) => {
        fs.writeFile(temp, data, { flag: 'w' }, function() {
            response.sendFile(temp);
        });
    });

但最好使用 toFile 而不是 toBuffer:

sharp('originalFile.jpg').
        resize(330,null).
        flatten().
        toFile('newFile.jpg', function(err){
            if(err){
                response.sendStatus(500);
                return;
            }
            response.sendFile('newFile.jpg');
        });

你可以這樣做

sharp(req.files[0].path).resize(400, 200).toFile('uploads/' + 'thumbnail-' + req.files[0].originalname, (err, sharp) => {
            if (err) {
                console.error(err);
            }
            else {
                console.log(sharp);
            }
        });

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM