Retrieve an image from the server, store it in localStorage, and display it

后端 未结 4 632
终归单人心
终归单人心 2021-02-01 10:12

This should be simple enough, but after wrestling with it for hours, I still can\'t get it to work. So far, all my attempts have resulted in the image becoming \'corrupted or tr

4条回答
  •  伪装坚强ぢ
    2021-02-01 10:53

    You can get the data uri (which will contain the base 64 encoding) via JavaScript using the HTML5 canvas element.

            // I'm assuming here you've put the image in an  tag on the page already.
            // If not, you'll need to adapt this a bit, or perhaps this approach is just
            // not right for your situation.
            var image = document.getElementById('id-of-image-you-want');
    
            var canvas = w.document.createElement("canvas"); 
            canvas.width = image.width;
            canvas.height = image.height;
    
            var ctx = canvas.getContext("2d");
            ctx.drawImage(image, 0, 0);
            try {
                var dataUri = canvas.toDataURL();    
            } catch (e) {
                console.log("D'oh!"); // Improve this error handling, obviously.
            }
    

    dataUri will now contain the data uri for the image which will contain, along with a short prefix, the base 64 encoding of the image.

    Be sure to add detection for canvas support. IE 8 and older do not support it.

提交回复
热议问题