将我的页面上的图像转换为base64

时间:2016-10-22 19:40:36

标签: javascript html5-canvas base64

我的页面上加载了一个图片,需要转换为base64。我目前正在使用以下内容:

    var c = document.createElement("canvas");
    var ctx = c.getContext("2d");
    var img = document.getElementById("additem_img");
    ctx.drawImage(img, 10, 10);
    console.log(c.toDataURL());

我在另一个StackOverflow问题中找到了。它似乎创建了一个base64字符串

数据:图像/ PNG; BASE64,iVBORw0KGgoAAAANSUhEUgAAASwAAACWCAYAAABkW7XSAAAEYklEQVR4Xu3UAQkAAAwCwdm / 9HI83BLIOdw5AgQIRAQWySkmAQIEzmB5AgIEMgIGK1OVoAQIGCw / QIBARsBgZaoSlAABg + UHCBDICBisTFWCEiBgsPwAAQIZAYOVqUpQAgQMlh8gQCAjYLAyVQlKgIDB8gMECGQEDFamKkEJEDBYfoAAgYyAwcpUJSgBAgbLDxAgkBEwWJmqBCVAwGD5AQIEMgIGK1OVoAQIGCw / QIBARsBgZaoSlAABg + UHCBDICBisTFWCEiBgsPwAAQIZAYOVqUpQAgQMlh8gQCAjYLAyVQlKgIDB8gMECGQEDFamKkEJEDBYfoAAgYyAwcpUJSgBAgbLDxAgkBEwWJmqBCVAwGD5AQIEMgIGK1OVoAQIGCw / QIBARsBgZaoSlAABg + UHCBDICBisTFWCEiBgsPwAAQIZAYOVqUpQAgQMlh8gQCAjYLAyVQlKgIDB8gMECGQEDFamKkEJEDBYfoAAgYyAwcpUJSgBAgbLDxAgkBEwWJmqBCVAwGD5AQIEMgIGK1OVoAQIGCw / QIBARsBgZaoSlAABg + UHCBDICBisTFWCEiBgsPwAAQIZAYOVqUpQAgQMlh8gQCAjYLAyVQlKgIDB8gMECGQEDFamKkEJEDBYfoAAgYyAwcpUJSgBAgbLDxAgkBEwWJmqBCVAwGD5AQIEMgIGK1OVoAQIGCw / QIBARsBgZaoSlAABg + UHCBDICBisTFWCEiBgsPwAAQIZAYOVqUpQAgQMlh8gQCAjYLAyVQlKgIDB8gMECGQEDFamKkEJEDBYfoAAgYyAwcpUJSgBAgbLDxAgkBEwWJmqBCVAwGD5AQIEMgIGK1OVoAQIGCw / QIBARsBgZaoSlAABg + UHCBDICBisTFWCEiBgsPwAAQIZAYOVqUpQAgQMlh8gQCAjYLAyVQl KgIDB8gMECGQEDFamKkEJEDBYfoAAgYyAwcpUJSgBAgbLDxAgkBEwWJmqBCVAwGD5AQIEMgIGK1OVoAQIGCw / QIBARsBgZaoSlAABg + UHCBDICBisTFWCEiBgsPwAAQIZAYOVqUpQAgQMlh8gQCAjYLAyVQlKgIDB8gMECGQEDFamKkEJEDBYfoAAgYyAwcpUJSgBAgbLDxAgkBEwWJmqBCVAwGD5AQIEMgIGK1OVoAQIGCw / QIBARsBgZaoSlAABg + UHCBDICBisTFWCEiBgsPwAAQIZAYOVqUpQAgQMlh8gQCAjYLAyVQlKgIDB8gMECGQEDFamKkEJEDBYfoAAgYyAwcpUJSgBAgbLDxAgkBEwWJmqBCVAwGD5AQIEMgIGK1OVoAQIGCw / QIBARsBgZaoSlAABg + UHCBDICBisTFWCEiBgsPwAAQIZAYOVqUpQAgQMlh8gQCAjYLAyVQlKgIDB8gMECGQEDFamKkEJEDBYfoAAgYyAwcpUJSgBAgbLDxAgkBEwWJmqBCVAwGD5AQIEMgIGK1OVoAQIGCw / QIBARsBgZaoSlACBB1YxAJfjJb2jAAAAAElFTkSuQmCC

但是当我尝试使用每个在线解码器解码时,我什么也得不到。 " additem_img" element是一个图像,其来源是来自远程网页的图像。我想使用canvas和base64创建本地副本。

1 个答案:

答案 0 :(得分:0)

试试这个:

<img id="additem_img" src="image.png">

<script>
    var c = document.createElement("canvas");
    var ctx = c.getContext("2d");

    var img = document.getElementById("additem_img");
    var w = img.width;
    var h = img.height;

    c.width = w;
    c.height = h;

    ctx.drawImage(img, 0, 0);
    console.log(c.toDataURL());
</script>