使用 archiver 和 sharp 调整和压缩图像流

Resizing and zipping image streams using archiver and sharp

我正在尝试下载一些图像,调整它们的大小,压缩它们,并使用流从端点提供服务。我正在使用 sharp for the resizing and archiver 进行压缩。我可以让这些包单独工作,但不能一起工作。

下面是一些示例代码:

const Hapi = require('hapi');
const archiver = require('archiver');
const sharp = require('sharp');
const request = require('request');

function foo() {
  return new Promise((resolve, reject) => {
    const imageStreams = [request('http://i.stack.imgur.com/tKsDb.png'), request('http://i.stack.imgur.com/EdUwb.png'), request('http://i.stack.imgur.com/5d55j.png')]

    const zip = archiver('zip');
    zip.on('error', e => console.log('zip error: ', e.message));
    zip.on('entry', entry => console.log('appended ', entry.name));

    resolve(zip);

    process.nextTick(() => {
      console.log('number of streams: ', imageStreams.length);

      imageStreams.map((stream, j) => {
        const resize = sharp().resize(100, 100);

        return stream.pipe(resize);
      })
      .forEach((resizedImageStream, i) => {
        console.log('appending ', i, ' to zip');
        zip.append(resizedImageStream, { name: `${i}.png` });
      });

      console.log('finalizing zip');
      zip.finalize();
    });
  });
}

const server = new Hapi.Server();
server.connection({port: 3000});

server.route({
  method: 'GET',
  path: '/',
  handler: (request, reply) => {
    foo().then(zip => reply(zip));
  }
})
server.start();

运行 它与: npm init --yes && npm install hapi archiver sharp request && node index.js

这将在 http://localhost:3000 处创建一个端点,它将无法将 zip 文件流式传输到响应。

以下各项将使下载工作:

但我无法让它同时处理多张图片和调整大小。

原来是sharp库的bug,现已修复here