为什么要节省价值" null" (尝试在encode64中保存图像)?

时间:2014-06-24 14:16:00

标签: javascript jquery

我正在尝试在encoded64中保存图像,而不是从本地存储中获取图像的值。但是我得到null值为什么?

这是我的小提琴: http://jsfiddle.net/sAH8w/7/

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");
    try {
    localStorage.setItem("elephant", dataURL);
}
catch (e) {
    alert('error')
    console.log("Storage failed: " + e);
}

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

1 个答案:

答案 0 :(得分:1)

这个小改动解决了这个问题:

 $('#save').click(function(){
    var image = new Image();
    image.src = "https://dl.dropboxusercontent.com/s/t2ywui846zp58ye/plus_minus_icons.png?m=";
    getBase64Image(image);

 })

工作小提琴:http://jsfiddle.net/robertrozas/sAH8w/15/

更新(获取按钮):http://jsfiddle.net/robertrozas/sAH8w/17/