简体   繁体   中英

Saving image to localstorage - canvas

I'm using html5 storage to store my image. It works great in chrome. In FireFox it works 8/10 times.

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

        console.log("line 1 : " + img.src);
        var dataURL = canvas.toDataURL('image/jpeg');
        console.log("line 2 : " + dataURL.replace(/^data:image\/(jpeg);base64,/, ""));
        return dataURL.replace(/^data:image\/(jpeg);base64,/, "");
    }

Sometimes it returns only "data,".

I see that the canvas size is 0x0:

canvas.width = img.width;
canvas.height = img.height;

Why is that happening?

If the height or width of the canvas is 0, the string "data:," is returned.

This is most likely the cause for some images to fail to receive a proper dataUrl.

Check your img elements and/or scripts to obtain and set the width and height of the canvas.

The auto width and height are only available after the image is loaded.

The function is trying to get the height/width before the image is loaded so I get 0x0. To solve that add img.onload before calling the save function.

function readURL(input, image, width, height) {
            if (input.files && input.files[0]) {

                var reader = new FileReader();

                reader.onload = function (e) {
                    //Save the image
                    var img = new Image();
                    img.src = e.target.result;
                    img.onload = function (e){
                        if (image.id == 'photo1') {
                            save(img, 'image1');
                        }
                        else {
                            save(img, 'image2');
                        }
                    }
                }
                reader.readAsDataURL(input.files[0]);
            }
        }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM