【问题标题】:Nodejs - How to zip multiple imagesNodejs - 如何压缩多个图像
【发布时间】:2020-05-08 08:02:06
【问题描述】:

我有一组图像 url,我希望能够检索所有图像并将它们压缩。我该怎么办?

【问题讨论】:

  • 需要先下载图片吗?还是已经下载了图片?
  • ^ 这些网址实际上是系统拍的吗?
  • 如果我的回答有帮助,请投票! :)

标签: javascript node.js


【解决方案1】:

要下载所有图片,可以使用request模块:

var fs = require('fs'),
    request = require('request');

var download = function(uri, filename, callback){
  request.head(uri, function(err, res, body){
    console.log('content-type:', res.headers['content-type']);
    console.log('content-length:', res.headers['content-length']);

    request(uri).pipe(fs.createWriteStream(filename)).on('close', callback);
  });
};
//Now, you can simply use `download(imageUrl,localFilename,function(){ /*return or print something here*/ });`
download('https://www.google.com/images/srpr/logo3w.png', 'google.png', function(){
  console.log('done');
});

要将所有文件(在您的情况下为图像)压缩到一个文件夹中,您应该尝试archiver lib:

var file_system = require('fs');
var archiver = require('archiver');

var output = file_system.createWriteStream('target.zip');
var archive = archiver('zip');

output.on('close', function () {
    console.log(archive.pointer() + ' total bytes');
    console.log('archiver has been finalized and the output file descriptor has closed.');
});

archive.on('error', function(err){
    throw err;
});

archive.pipe(output);
archive.bulk([
    { expand: true, cwd: 'source', src: ['**'], dest: 'source'}
]);
archive.finalize();

或zipFolderlib:

var zipFolder = require('zip-folder');

zipFolder('/path/to/the/folder', '/path/to/target.zip', function(err) {
    if(err) {
        console.log('Oh no! Error!', err);
    } else {
        console.log('Nice! :)');
    }
});

【讨论】:

    猜你喜欢
    • 2020-06-22
    • 2019-03-08
    • 1970-01-01
    • 1970-01-01
    • 2019-05-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-01-28
    相关资源
    最近更新 更多