【问题标题】:Copying an image, reading its metadata, and writing back with streams and sharp复制图像,读取其元数据,并使用流和锐化回写
【发布时间】:2020-03-19 08:44:58
【问题描述】:

我正在尝试编写一个 Lambda 函数,该函数获取存储为 S3 对象的图像,读取其高度和宽度,并将其移动到同一存储桶中的不同前缀。然后,它在保持原始纵横比的同时获取图像并调整其大小,并将调整后的图像写入对象的原始前缀。

我的代码基于示例here。总的来说,我对 NodeJS 和 JS 完全陌生。

为了实现我想要的,我设置了两个不同的管道。两者都由 3 个流组成。第一个管道有一个读取流、一个获取元数据的流和一个写入流。第二个管道是读取、调整大小、写入。

我不确定如何正确地从流中读取图像的元数据。整个代码是here。我将尝试在问题中仅包含相关的 sn-ps。

此函数旨在用作管道的一部分。它旨在读取图像的高度和宽度并将它们存储在变量中。

// Get size from stream (sharp)
const getSizeFromStream = () => {
    const pass = new stream.PassThrough();
    const metadata = sharp(pass).metadata().then(metadata =>
        {
            return {
                writeStream: pass,
                width: metadata.width,
                height: metadata.height
            };

        });
};

这通过管道调用:

            const readStreamOrig = readStreamFromS3(params);

            const {
                passThroughStream,
                origWidth,
                origHeight
            } = getSizeFromStream();

            const {
                writeStreamOrig,
                uploadFinishedOrig
            } = writeStreamToS3({Bucket: params[0], Key: newKey});

            readStreamOrig
                .pipe(passThroughStream)
                .pipe(writeStreamOrig);

读写流与触发 Lambda 函数的 S3 对象交互的地方。

但是,这不起作用,产生以下两个错误:

{
    "errorType": "TypeError",
    "errorMessage": "Cannot destructure property `passThroughStream` of 'undefined' or 'null'."
}
{
    "errorType": "Runtime.UnhandledPromiseRejection",
    "errorMessage": "Error: Input file is missing or of an unsupported image format",
}

我不确定流是如何传递给流的,以及如何从函数中访问它们。我也不确定从这样的流中分配变量是否有意义。读取元数据的函数应该怎么写?

【问题讨论】:

    标签: node.js serverless sharp


    【解决方案1】:

    我会考虑更多:
    - 将 S3 上的图像从其名称移动到带有前缀的名称
    - 从前缀图像中读取流,使用尖管调整图像大小/进行转换,写回 S3 流到无前缀图像

    锐流示例:

    // Before this, use S3 API to move the image to its prefixed name
    // Then...
    
    const readStream = readStreamFromS3(params); // Read prefixed image from S3
    
    const resizeStream = sharp()
      .resize(200, 200)
      .png();
    
    const s3WriteStream = writeStreamToS3({
      Bucket: unprefixedBucket,
      Key: unprefixedKey,
    });
    
    readStream
      .pipe(resizeStream)
      .pipe(s3WriteStream);
    

    还是我弄错了,您实际上还想从图像中提取宽度和高度?

    【讨论】:

    • 确实,我也想提取原图的元数据。
    • 那会怎样?先将 S3 对象设置为锐化,然后使用流移动它?
    猜你喜欢
    • 2014-03-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-09-11
    • 1970-01-01
    • 1970-01-01
    • 2020-10-20
    相关资源
    最近更新 更多