我有一个包含图片的iframe。图像源链接到S3
存储桶中的图像。我需要在Base64中对此图像进行编码,并将iframe的正文保存在数据库中。
我该怎么做?
答案 0 :(得分:0)
试试这个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,/, "");
}
答案 1 :(得分:0)
如果您将 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 钩子):
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}