h5+FileReader

来源:互联网 发布:郝蕾骂河南人 知乎 编辑:程序博客网 时间:2024/05/21 19:39

页面文件标签

 <input type="file" id="GIF_action_picture" name="file_action_picture"                                           onchange="selectImage(this,'GIF_action_picture','image2');"   accept="image/gif,image/jpeg,image/jpg,image/png" />

js

//上传图片 id是文件id imageId是图片id  function selectImage(file,id,imageId) {    if (!file.files || !file.files[0]) {        return;    }    var suffix=file.files[0].name.replace(/.+\./,"");    var size = file.files[0].size;    var type = file.files[0].type;    var reader = new FileReader();    reader.onload = function (evt) {        /*将bsae64码转成jpeg图片*/      var result = evt.target.result;        var str1 = result.substr(result.indexOf("base64"));        result = "data:image/jpg;" + str1;        $('#'+imageId+'').attr('src',result);        $('#'+id+'').parent().css("display","none");        $('#'+imageId+'').parent().css("display","block");        /*将bsae64码转成jpeg图片*/        compressImg(result, 280, function (data) {//压缩完成后执行的callback            document.getElementById(''+id+'').src = data;            image = data;        },suffix);    }   reader.readAsDataURL(file.files[0]);}//function compressImg(imgData, maxWidth, onCompress,suffix) {    if (!imgData) return;    onCompress = onCompress || function () { };    maxWidth = maxWidth||280 ;//默认最大宽度280px    var canvas = document.createElement('canvas');    var img = new Image();    img.onload = function () {        if (img.width > maxWidth) {//按最大高度等比缩放            img.height *= maxWidth / img.width;            img.width = maxWidth;        }        canvas.height = img.height;        canvas.width = img.width;        var ctx = canvas.getContext("2d");        ctx.clearRect(0, 0, canvas.width, canvas.height); // canvas清屏        //重置canvans宽高 canvas.width = img.width; canvas.height = img.height;        ctx.drawImage(img, 0, 0, img.width, img.height); // 将图像绘制到canvas上         onCompress(canvas.toDataURL("image/jpg"));//必须等压缩完才读取canvas值,否则canvas内容是黑帆布    };    // 记住必须先绑定事件,才能设置src属性,否则img没内容可以画到canvas    img.src = imgData;}
原创粉丝点击