【问题标题】:encode web url image in base64 in JS在 JS 中用 base64 编码 web url 图像
【发布时间】:2019-02-13 03:02:38
【问题描述】:

我正在尝试将 zip 文件从 html 页面加载到 pc 硬盘,但现在失败了,为了保存一个应该以 base64 编码的图像,如果它是一个 web url 图像,如何进行思考。

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>

    </script>
<img id = "myImage" src="http://files.smashingmagazine.com/wallpapers/feb-18/love-work/cal/feb-18-love-work-cal-320x480.png">
<input type = 'button' onclick="func()" value = "press me">
<script >
    function getBase64Image(img){
        var canvas = document.createElement("canvas");
        canvas.width = img.width;
        canvas.height = img.height;
        var ctx = canvas.getContext("2d");
        ctx.drawImage(img,0,0);
        var dataUrl = canvas.toDataURL("image/png");
        return dataUrl.replace(/^data:image\/(png|jpg);base64,/,"")
    }





    function func() {


var image = document.querySelector("#myImage");
var base64 = getBase64Image(image);

alert(base64);


}
</script>
</body>
</html>

【问题讨论】:

  • 编码前可能需要解压
  • 我没有 zip 我会在获取图像的 base64 编码时创建它
  • 因此,您需要一种方法将图像 URL 转换为 base64,然后将其压缩,然后页面可以下载。我说对了吗?
  • 是的,之后我将使用 jszip 下载它 zip.file("hello.png", base64, {base64:true});警报(base64); zip.generateAsync({type:"base64"}).then(function(blob) { location.href="data:application/zip;base64,"+blob; });

标签: javascript image url download base64


【解决方案1】:

我认为你可以通过使用 httprequest 对象来加载文件。

var req = new XMLHttpRequest();
req.withCredentials = true;
req.open("GET", sFileUrl, false); // 'false': synchronous.
req.send(null);
//return req.response;

如果需要base64,可以将字节数组转成base64。

var u8 = new Uint8Array(req.response);
var b64encoded = btoa(String.fromCharCode.apply(null, u8));
return b64encoded;

确保您可以访问 URL 图片。 希望对您有所帮助。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-12-26
    • 1970-01-01
    • 2015-10-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多