使用localStorage存储时的空白图像&检索PNG

时间:2016-02-13 23:20:38

标签: javascript jquery html5 local-storage

尝试加载&从localstorage检索图像。我猜内容安全性不是问题。

某处代码破坏了未在本地存储中正确存储的图像或未从本地存储中正确加载的图像。

以下是用于检查图像是否可从localstorage获取的代码。如果从会话中获得,则从localstorage获取它。否则从URL获取它并显示图像并存储在localstorage中。

以下代码将在pagebeforecreate

执行
    var dataImage = localStorage.getItem('ses_image');

    var img = $('<img crossorigin="anonymous" width="100%" height="100%" id="img_menu-item" style="height: 100%;width:100%">');
    jQuery('#pg_home_content').append(img);

    if(dataImage){
        bannerImg = document.getElementById('img_menu-item');
        bannerImg.src = dataImage;
        jQuery('#pg_home_content').append(bannerImg);
    }else{
        img.attr('src', 'http://example.com/myimage.png');
        bannerImage = document.getElementById('img_menu-item');
        bannerImage.setAttribute('crossOrigin', 'anonymous');
        imgData = getBase64Image(bannerImage);
        localStorage.setItem('ses_image', imgData);
    }

getBase64Image

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;
}

当我console.log(dataURL)时,它会生成以下输出,我猜错了...

data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAGQAAABkCAYAAABw4pVUAAABZUlEQVR4Xu3TQREAAAiEQK9/aWvsAxMw4O06ysAommCuINgTFKQgmAEMp4UUBDOA4bSQgmAGMJwWUhDMAIbTQgqCGcBwWkhBMAMYTgspCGYAw2khBcEMYDgtpCCYAQynhRQEM4DhtJCCYAYwnBZSEMwAhtNCCoIZwHBaSEEwAxhOCykIZgDDaSEFwQxgOC2kIJgBDKeFFAQzgOG0kIJgBjCcFlIQzACG00IKghnAcFpIQTADGE4LKQhmAMNpIQXBDGA4LaQgmAEMp4UUBDOA4bSQgmAGMJwWUhDMAIbTQgqCGcBwWkhBMAMYTgspCGYAw2khBcEMYDgtpCCYAQynhRQEM4DhtJCCYAYwnBZSEMwAhtNCCoIZwHBaSEEwAxhOCykIZgDDaSEFwQxgOC2kIJgBDKeFFAQzgOG0kIJgBjCcFlIQzACG00IKghnAcFpIQTADGE4LKQhmAMNpIQXBDGA4LQQL8oTPAGUY76lBAAAAAElFTkSuQmCC

这是第一次加载图像,从第二次开始,我得到一张空白图片......不确定我错过了什么?

1 个答案:

答案 0 :(得分:1)

将图像写入本地存储时,图像尚未完全加载。空白图像会存储在本地存储中,而是在后续访问时检索。

要确保在本地写入图像之前加载图像,请为图像创建onload事件处理程序。

在您的代码中,更改:

    img.attr('src', 'http://example.com/myimage.png');
    bannerImage = document.getElementById('img_menu-item');
    bannerImage.setAttribute('crossOrigin', 'anonymous');
    imgData = getBase64Image(bannerImage);
    localStorage.setItem('ses_image', imgData);

为:

    console.log('loaded from url');
    bannerImage = document.getElementById("img_menu-item");
    bannerImage.setAttribute('crossOrigin', 'anonymous');

    // set the source of the image, equivalent to img.attr('src',...), but
    // slightly more performant
    img[0].src = "http://demo.jeema.org/mob20/media/com_jeemasmsmobile/menuicons/book.png";
    // delay writing to localstorage, until the image loads completely:
    img[0].onload = function () {
        imgData = getBase64Image(bannerImage);
        console.log('writing to local storage:\n' + imgData);
        localStorage.setItem('ses_image', imgData);
        console.log('image stored');
    }