将图像保存到本地存储 - canvas

Saving image to localstorage - canvas

我正在使用 html5 存储来存储我的图像。 它在 chrome 中运行良好。在 FireFox 中它工作 8/10 次。

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

有时 returns 仅 "data,"。

我看到 canvas 大小是 0x0:

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

为什么会这样?

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

这很可能是某些图片无法接收到正确的 dataUrl 的原因。

检查您的 img 元素 and/or 脚本以获取和设置 canvas.

的宽度和高度

自动宽度和高度仅在加载图像后可用。

该函数试图在加载图像之前获取 height/width,所以我得到 0x0。要解决这个问题,请在调用保存函数之前添加 img.onload

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