繁体   English   中英

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

[英]How to Convert buffer into image using nodejs?

这是我从 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)

OUTPUT

{
  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>
}

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类的操作 - 我不确定来自 C 的 ZA8CFDE6331BD59EB2AC96F891 是什么样的。

话虽如此,我在本地将此图像保存为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}" />`);
  });
});
// ...

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

按照 function 将缓冲区转换为字符串

  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)

1.尝试使用Jimp库将图像转换为缓冲区,也可以保存在数据库中。

 const imagePath = `path/to/image`;
  const jimpImageToBuffer = await jimp
    .read(imagePath) // read image from path
    .then((ele) => {
      const mimeForImage = ele._originalMime;
      return ele.getBufferAsync(mimeForImage); // convert image to buffer(compatiable to save to database).
    })
    .catch((err) => console.log(err));
  console.log(jimpImageToBuffer); // <- image in buffer format

检查以下链接以了解图像到缓冲区的 jimp 转换的实现和完整说明。

https://stackoverflow.com/a/72798711/18383251

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM