【问题标题】:Encode image to Base64 from Amazon S3从 Amazon S3 将图像编码为 Base64
【发布时间】:2016-12-26 20:01:49
【问题描述】:

我有一个包含图像的 iframe。图像源链接到 S3 存储桶中的图像。我需要将此图像编码为Base64 并将 iframe 的正文保存在数据库中。

我该怎么做?

【问题讨论】:

标签: javascript jquery


【解决方案1】:

试试这个How to access the <img /> in document from iframe?

$('#Iframe1').contents().find('img').css({'width':'100%','height':'90%'});

然后从这里使用这个函数Get image data in JavaScript?

function getBase64Image(img) {
    // Create an empty canvas element
    var canvas = document.createElement("canvas");
    canvas.width = img.width;
    canvas.height = img.height;

    // Copy the image contents to the canvas
    var ctx = canvas.getContext("2d");
    ctx.drawImage(img, 0, 0);

    // Get the data-URL formatted image
    // Firefox supports PNG and JPEG. You could check img.src to
    // guess the original format, but be aware the using "image/jpg"
    // will re-encode the image.
    var dataURL = canvas.toDataURL("image/png");

    return dataURL.replace(/^data:image\/(png|jpg);base64,/, "");
}

【讨论】:

  • 非常感谢您的回答,但是当我尝试这样做时: var image = $('#Iframe1').contents().find('img'); console.log("Base64" + current.getBase64Image(image));我有错误“提供的值不是 HTMLImageElement 的类型”
  • 注销image的值,告诉我是什么
【解决方案2】:

如果您将 s3 存储桶对象存储在二进制/blob 中, 例如,你在服务器上做了类似的事情:

...

//event.body - base64 received from client or REST
       
let decodedImage = Buffer.from(event.body.replace(/^data:(image|application)\/\w+;base64,/, ""), "base64")

        var params = {
          Bucket: bucket,
          Key: key, // 
          Body: decodedImage,
          ContentEncoding: 'base64',
          ACL: 'public-read',
          ContentType: event.headers["Content-Type"],
        }


        // Uploading files to the bucket :
...
        s3.putObject(params, function (err, data) {

接收它并将其转换回base64可以在前端使用代码完成(例如React hook):

const blobToBase64 = (blob) => {
  const reader = new FileReader()
  reader.readAsDataURL(blob)
  return new Promise((rs, rj) => {
    reader.onloadend = () => {
      rs(reader.result)
    }
    reader.onerror = rj
  })
}

function useImage({s3Link}) {
  const [src, setSrc] = React.useState(null)

  React.useEffect(() => {
    async function query({link}) {
      //link is link to s3 bucket URL link e.g
      // const link = s3.getSignedUrl('getObject', {
      //   Bucket: bucketnamw,
      //   Key: key,
      //   Expires: 30,
      // })

      const r = await fetch(link)
      const blob = await r.blob()
      const base64 = await blobToBase64(blob)
      console.log(`base64!`, base64)
      setSrc(base64)
    }

    if (s3Link) {
      query({link: s3Link})
    }
  }, [s3Link, setSrc])

  return [{src}]
}

...

const [hookImage] = useImage({s3Link})

查看:

 {hookImage.src ? <img src={hookImage.src} /> : null}

【讨论】:

    猜你喜欢
    • 2015-09-05
    • 2011-11-22
    • 2014-06-26
    • 2018-07-16
    • 2017-01-09
    • 2022-11-30
    • 2016-05-22
    • 2023-03-15
    • 1970-01-01
    相关资源
    最近更新 更多