将上传的图像保存到localStorage(chrome扩展名) [英] Saving an uploaded image to localStorage (chrome extension)

查看:134
本文介绍了将上传的图像保存到localStorage(chrome扩展名)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我无法确定如何将上传的图像存储在localStorage中,这是由用户在我的选项页面中输入的。关于如何做的文件太多了,因为有一段时间它是已知错误,我无法在Stack上找到任何示例。有一些关于如何在页面上保存图像的示例,但在输入图像上没有任何内容。

I'm having trouble finding how exactly I would store an uploaded image in localStorage, as inputted by a user in my options page. There isnt too much documentation on how to do it because for awhile it was a known error and I couldnt find any examples on Stack. There's some examples on how to save an image already on a page but nothing on an inputed image.

我所拥有的只是HTML,但我想是javascript在运行后面需要访问输入的值或什么(?)。

All i have is the HTML, but I imagine that the javascript running in the back needs to access the value of the input or something (?).

<input id="uploadImage" type="file" accept="image/*" />

然后在用户选择文件后,输入的值为 C :\fakepath\some_image.jpg 。我不想存储文件路径,但如果可能的话,存储实际图像。

Then after the user chooses a file, the value of the input is C:\fakepath\some_image.jpg. I dont want to store the filepath but store the actual image, if possible.

$("#uploadImage").change(function(){
    alert($("#uploadImage").val());
});

编辑:

我找到了一个样本如何从此堆栈主题,但文件路径我来自 $(#uploadImage)。val()无效(所以即使文件路径有效,我也不知道这个方法是否有效)

I found a sample on how to do it from this stack topic, but the filepath that I get from $("#uploadImage").val() doesnt work (So I dont know if this method work work even if the filepath was valid)

var img = new Image();
img.src = $("#uploadImage").val();
img.load = function() {
    var canvas = document.createElement('canvas');
    document.body.appendChild(canvas);
    var context = canvas.getContext('2d');
    context.drawImage(img, 0, 0);
    var data = context.getImageData(x, y, img.width, img.height).data;
    localStorage['uploadedImage'] = data; // save image data
};


推荐答案

这需要FileReader API,并且只是一个修改过的这个答案的版本(参考:将图像加载到< img> from< input file> ):

This requires the FileReader API, and is just a modified version of this answer (ref: Loading an image to a <img> from <input file>):

    var input = document.getElementById('uploadImage');
    input.onchange = function(evt){
        var tgt = evt.target || window.event.srcElement, 
            files = tgt.files;

        if (FileReader && files && files.length) {
            var fr = new FileReader();
            fr.onload = function () {
                localStorage['foo'] = fr.result;
            }
            fr.readAsDataURL(files[0]);
        }
    }

然后您可以将其作为背景图像应用类似于:

You could then apply it as a background image by doing something like:

var el = document.querySelector('body');
el.style.backgroundImage = 'url(' + localStorage['foo'] + ')';

这篇关于将上传的图像保存到localStorage(chrome扩展名)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆