How to save an image to localStorage and display it on the next page?

后端 未结 7 2072
逝去的感伤
逝去的感伤 2020-11-22 07:31

So, basically, I need to upload a single image, save it to localStorage, then display it on the next page.

Currently, I have my HTML file upload:

<         


        
相关标签:
7条回答
  • 2020-11-22 07:51

    To whoever also needs this problem solved:

    Firstly, I grab my image with getElementByID, and save the image as a Base64. Then I save the Base64 string as my localStorage value.

    bannerImage = document.getElementById('bannerImg');
    imgData = getBase64Image(bannerImage);
    localStorage.setItem("imgData", imgData);
    

    Here is the function that converts the image to a Base64 string:

    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,/, "");
    }
    

    Then, on my next page I created an image with a blank src like so:

    <img src="" id="tableBanner" />
    

    And straight when the page loads, I use these next three lines to get the Base64 string from localStorage, and apply it to the image with the blank src I created:

    var dataImage = localStorage.getItem('imgData');
    bannerImg = document.getElementById('tableBanner');
    bannerImg.src = "data:image/png;base64," + dataImage;
    

    Tested it in quite a few different browsers and versions, and it seems to work quite well.

    0 讨论(0)
  • 2020-11-22 07:51

    I have come up with the same issue, instead of storing images, that eventually overflow the local storage, you can just store the path to the image. something like:

    let imagen = ev.target.getAttribute('src');
    arrayImagenes.push(imagen);
    
    0 讨论(0)
  • 2020-11-22 07:52

    If your images keep getting cropped, here's some code to get the dimensions of the image file before saving to localstorage.

    First, I would create some hidden input boxes to hold the width and height values

    <input id="file-h" hidden type="text"/>
    <input id="file-w" hidden type="text"/>
    

    Then get the dimensions of your file into the input boxes

    var _URL = window.URL || window.webkitURL;
    $("#file-input").change(function(e) {
        var file, img;
        if ((file = this.files[0])) {
            img = new Image();
            img.onload = function() {
                $("#file-h").val(this.height);
                $("#file-w").val(this.width);
            };
            img.onerror = function() {
                alert( "not a valid file: " + file.type);
            };
            img.src = _URL.createObjectURL(file);
        }
    });
    

    Lastly, change the width and height objects used in the getBase64Image() function by pointing to your input box values

    FROM

    function getBase64Image(img) {
        var canvas = document.createElement("canvas");
        canvas.width = img.width;
        canvas.height = img.height;
    

    TO

    function getBase64Image(img) {
        var canvas = document.createElement("canvas");
        canvas.width = $("#file-w").val();
        canvas.height = $("#file-h").val();
    

    Also, you are going to have to maintain a size of about 300kb for all files. There are posts on stackoverflow that cover file size validation using Javascript.

    0 讨论(0)
  • 2020-11-22 08:04

    I wrote a little 2,2kb library of saving image in localStorage JQueryImageCaching Usage:

    <img data-src="path/to/image">
    <script>
        $('img').imageCaching();
    </script>
    
    0 讨论(0)
  • 2020-11-22 08:07

    "Note that you need to have image fully loaded first (otherwise ending up in having empty images), so in some cases you'd need to wrap handling into: bannerImage.addEventListener("load", function () {}); – yuga Nov 1 '17 at 13:04"

    This is extremely IMPORTANT. One of the the options i'm exploring this afternoon is using javascript callback methods rather than addEventListeners since that doesn't seem to bind correctly either. Getting all the elements ready before page load WITHOUT a page refresh is critical.

    If anyone can expand upon this please do - as in, did you use a settimeout, a wait, a callback, or an addEventListener method to get the desired result. Which one and why?

    0 讨论(0)
  • 2020-11-22 08:11

    You could serialize the image into a Data URI. There's a tutorial in this blog post. That will produce a string you can store in local storage. Then on the next page, use the data uri as the source of the image.

    0 讨论(0)
提交回复
热议问题