如何使用nodejs将缓冲区转换为图像?

时间:2020-07-03 05:02:55

标签: node.js amazon-s3

这是我从S3存储桶获取图像的代码,但结果在缓冲区中,我需要将其作为图像。请告诉我这样做

const AWS = require('aws-sdk')
const fs = require('fs')
const express = require('express')
const app = express()
app.get('/', (req, res) => {
  const s3 = new AWS.S3({
    accessKeyId: '################',
    secretAccessKey: '###############################',
    region: '###########'
  })

  const params = {
    Bucket: '#########',
    Key: '########'
  }
  s3.getObject(params, (err, rest) => {
    res.send(rest)
  })
})

app.listen(3000)

输出

{
  AcceptRanges: 'bytes',
  LastModified: 2020-06-29T10:42:17.000Z,
  ContentLength: 338844,
  ETag: '"769af0d798cd0486993711bc63340bd0"',
  ContentType: 'application/octet-stream',
  Metadata: {},
  Body: <Buffer ff d8 ff e0 00 10 4a 46 49 46 00 01 01 00 00 01 00 01 00 00 ff db 00 84 00 02 02 02 
  02 02 02 02 02 02 02 03 03 02 03 03 04 03 03 03 03 04 06 04 04 04 ... 338794 
  more bytes>
}

2 个答案:

答案 0 :(得分:0)

TLDR;

/**
 * FINAL/WORKING SOLUTION
 */

// ...
app.get('/', (req, res) => {
  const s3 = new AWS.S3({
    accessKeyId: '-',
    secretAccessKey: '-',
    region: '-',
  });

  const params = {
    Bucket: '-',
    Key: '-',
  };

  s3.getObject(params, (err, rest) => {
    if (err) throw err;

    const b64 = Buffer.from(rest.Body).toString('base64');
    // CHANGE THIS IF THE IMAGE YOU ARE WORKING WITH IS .jpg OR WHATEVER
    const mimeType = 'image/png'; // e.g., image/png
    
    res.send(`<img src="data:${mimeType};base64,${b64}" />`);
  });
});
// ...

原始答案

您将需要使用node来“渲染”图像。也就是将响应作为<img />标签发送。.

// ...
app.get('/', (req, res) => {
  const s3 = new AWS.S3({
    accessKeyId: '-',
    secretAccessKey: '-',
    region: '-',
  });

  const params = {
    Bucket: '-',
    Key: '-',
  };

  s3.getObject(params, (err, rest) => {
    if (err) throw err;

    const b64 = Buffer.from(rest).toString('base64');
    // NOTE: 
    // Because 'rest' appears to be a buffer, you might not 
    // need to do `Buffer.from(...)`,you may have to do something like:
    /** const b64 = rest.toString('base64'); **/
    const mimeType = 'image/png'; // e.g., image/png
    
    res.send(`<img src="data:${mimeType};base64,${b64}" />`);
  });
});
// ...

编辑1:

我认为问题与从S3返回数据的方式有关。您可能需要执行rest.Bodyrest.body之类的操作-我不确定来自哪个对象S3看起来像。

话虽如此,我在本地将this image保存为sample.png,并使用下面的代码加载了它-很好。这可以证明问题与S3如何将数据返回给您有关。

const fs = require('fs');
const express = require('express');
const app = express();

app.get('/', (req, res) => {
  // Simulate getting data from S3 (aka data as buffer)
  const rest = Buffer.from(fs.readFileSync('./sample.png'));

  console.log('typeof rest = ' + typeof rest + '\r\n\r\n', rest);
  // typeof rest = object
  //
  // <Buffer 89 50 4e 47 0d 0a 1a 0a 00 00 00 0d 49 48 44 52 00 00 01 34 00 00 00 a4 08 03 00 00 00 2e 4e 22 5a 00 00 00 a2 50 4c 54 45 f7 f7 f7 cd 00 00 d1 00 00 ... 6360 more bytes>


  const b64 = rest.toString('base64');
  const mimeType = 'image/png'; // e.g., image/png

  res.send(`<img src="data:${mimeType};base64,${b64}" />`);
});

app.listen(3000);

编辑2:

您似乎需要这样做:

// ...
app.get('/', (req, res) => {
  const s3 = new AWS.S3({
    accessKeyId: '-',
    secretAccessKey: '-',
    region: '-',
  });

  const params = {
    Bucket: '-',
    Key: '-',
  };

  s3.getObject(params, (err, rest) => {
    if (err) throw err;

    const b64 = Buffer.from(rest.Body).toString('base64');
    // IF THE ABOVE LINE DOES NOT WORK, TRY THIS:
    // const b64 = rest.Body.toString('base64');

    // CHANGE THIS IF THE IMAGE YOU ARE WORKING WITH IS .jpg OR WHATEVER
    const mimeType = 'image/png'; // e.g., image/png
    
    res.send(`<img src="data:${mimeType};base64,${b64}" />`);
  });
});
// ...

答案 1 :(得分:0)

首先,让我们将缓冲区转换为字符串(在这种情况下,我们使用base64字符串) 然后,返回一个简单的html页面以显示base64字符串图像。

此函数会将缓冲区转换为字符串

  const encode = (data) => {
    let buf = Buffer.from(data);
    let base64 = buf.toString('base64');
    return base64
  }

将html页面发送给客户端:

    const html = `<html><body><img src='data:image/jpeg;base64,${encode(rest.Body)}'/></body></body></html>`
    res.send(html)

如您所见,rest.Body是图像的缓冲区内容。

最终代码:

const AWS = require('aws-sdk')
const fs = require('fs')
const express = require('express')
const app = express()
app.get('/', (req, res) => {
  const s3 = new AWS.S3({
    accessKeyId: '################',
    secretAccessKey: '###############################',
    region: '###########'
  })

  const params = {
    Bucket: '#########',
    Key: '########'
  }

  const encode = (data) => {
    let buf = Buffer.from(data);
    let base64 = buf.toString('base64');
    return base64
  }

  s3.getObject(params, (err, rest) => {
    const html = `<html><body><img src='data:image/jpeg;base64,${encode(rest.Body)}'/></body></body></html>`
    res.send(html)
  })
})

app.listen(3000)