簡體   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