簡體   English   中英

使用 Node.js 和 Google Cloud Storage 壓縮圖像

[英]Compressing Images with Node.js and Google Cloud Storage

我想在用戶將圖片上傳到我的網站后調整大小和壓縮圖片。 似乎有很多使用節點調整圖像大小的選項(例如https://github.com/lovell/sharp ),但我也想壓縮圖像以節省磁盤空間並允許更快的服務次。 是否有圖書館或其他使這成為可能的東西?

這是我當前(運行)路線的簡化版本:

var router = require('express').Router();
var bucket = require('../modules/google-storage-bucket');
var Multer = require('multer');
var multer = Multer({
  storage: Multer.memoryStorage(),
  limits: {
    fileSize: 5 * 1024 * 1024 // no larger than 5mb
  }
});

// Process the file upload and upload to Google Cloud Storage.
router.post('/', multer.single('file'), (req, res) => {

  // rejecting if no file is uploaded
  if (!req.file) {
    res.status(400).send('No file uploaded.');
    return;
  }

  // Create a new blob in the bucket and upload the file data.
  var blob = bucket.file('fileName');
  var blobStream = blob.createWriteStream();

  blobStream.on('error', (err) => {
    console.log('error', err);
    res.send(500);
  });

  blobStream.on('finish', () => {
    console.log('everything worked!')
  });

  blobStream.end(req.file.buffer);
});

module.exports = router;

Sharp 有用於調整圖像壓縮的 API。 例如:

https://sharp.pixelplumbing.com/api-output#jpeg

列出 JPEG 寫入的選項。 您可以調整 JPEG 壓縮器上的一系列旋鈕來調整它以獲得您想要的性能/壓縮/質量權衡。

在最好的情況下,您最多可以將壓縮率提高約 30%,老實說,這對我來說有點微不足道。 它不太可能對您的頁面大小或加載時間產生重大影響。

就存儲節省而言,最好的解決方案是根本不存儲圖像——Sharp 足夠快,您可以根據需要簡單地生成所有圖像(大多數動態圖像大小調整 Web 代理使用Sharp 作為引擎)。 這是一個真正可以為您省錢並使您的頁面看起來更好的更改。

根據我的經驗,我會推薦imagemin 我已經將它用作 Gulp 插件,因此您可以 100% 地在您的項目中使用它。 但您還必須下載第三方模塊:imagemin-pngquant 和 imagemin-jpegtran。

希望你欣賞它:)

暫無
暫無

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

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