How to save a image to HTML5 filesystem with the url of image

后端 未结 5 1547
青春惊慌失措
青春惊慌失措 2021-01-03 05:26

I am trying to use HTML5 system to store images of my website, and I find there are many example to show how to store a local image to your chrome file system but I can\'t f

5条回答
  •  鱼传尺愫
    2021-01-03 06:01

    I find a way to do this.

    use canvans.toDataURL to transfer data format.

    var img = new Image();
                    var cvs = document.createElement('canvas');
                    var ctx  = cvs.getContext("2d");
                    img.src = file;
                    img.onload = function(){
                        cvs.width = img.width;
                        cvs.height = img.height;
                        ctx.drawImage(img, 0, 0);
                        var imd = cvs.toDataURL(contentType[extname]);
                        var ui8a = convertDataURIToBinary(imd);
                        var bb = new BlobBuilder();
                        bb.append(ui8a.buffer);
                        fs.root.getFile(path, {create: true}, function(fileEntry) {
                            // Create a FileWriter object for our FileEntry (log.txt).
                            fileEntry.createWriter(function(fileWriter) {
                                fileWriter.onwriteend = function(e) {
                                    console.log('Write completed.');
                                    callback && callback("test.jpg");
                                };
    
                                fileWriter.onerror = function(e) {
                                    console.log('Write failed: ' + e.toString());
                                };
    
                                fileWriter.write(bb.getBlob(contentType[extname]));
                            });
                        });
                    };
    
    
    
        function convertDataURIToBinary(dataURI) {
        var BASE64_MARKER = ';base64,';
        var base64Index = dataURI.indexOf(BASE64_MARKER) + BASE64_MARKER.length;
        var base64 = dataURI.substring(base64Index);
        var raw = window.atob(base64);
        var rawLength = raw.length;
        var array = new Uint8Array(new ArrayBuffer(rawLength));
    
        for (i = 0; i < rawLength; i++) {
            array[i] = raw.charCodeAt(i);
        }
        return array;
    }
    

    I get help from here jsfiddle

提交回复
热议问题