• 0
  • 0

JS 新窗口打开base64图片

2019-12-07 119 0 admin 所属分类:Javascript
$('img').click(function(e) {
    const img = new Image();
    img.src = $(this).attr('src');
    const newWin = window.open("", "_blank");
    newWin.document.write(img.outerHTML);
    newWin.document.title = "查看图片"
    newWin.document.close();
});

将文件图片转换成base64格式

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, img.width, img.height);
    var ext = img.src.substring(img.src.lastIndexOf(".") + 1).toLowerCase();
    var dataUrl = canvas.toDataURL("images/" + ext);
    return dataUrl;
};
var img = "images/1.png";
var image = new Image();
image.src = img;
image.onload = function() {
    var base64 = getBase64Image(image);
    document.getElementsByClassName("img")[0].setAttribute("src", base64)
}


返回顶部