H5 上传图片时候如何预览图

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/adley_app/article/details/87877734

原理是用js获取input file的图像流,然后赋给img标签的src属性,然后再设置这个img的css,就能得到你要的效果了,代码如下

var demo_h5_upload_ops = {
    init:function(){
        this.eventBind();
    },
    eventBind:function(){
        var that = this;
        $("#upload").change(function(){
            var reader = new FileReader();
            reader.onload = function (e) {
                that.compress(this.result);
            };
            reader.readAsDataURL(this.files[0]);
        });
    },
    compress : function (res) {
        var that = this;
        var img = new Image(),
            maxH = 300;
 
        img.onload = function () {
            var cvs = document.createElement('canvas'),
                ctx = cvs.getContext('2d');
 
            if(img.height > maxH) {
                img.width *= maxH / img.height;
                img.height = maxH;
            }
            cvs.width = img.width;
            cvs.height = img.height;
 
            ctx.clearRect(0, 0, cvs.width, cvs.height);
            ctx.drawImage(img, 0, 0, img.width, img.height);
            var dataUrl = cvs.toDataURL('image/jpeg', 1);
            $(".img_wrap").attr("src",dataUrl);
            $(".img_wrap").show();
            // 上传略
            that.upload( dataUrl );
        };
 
        img.src = res;
    },
    upload:function( image_data ){
        /*这里写上次方法,图片流是base64_encode的*/
    }
};
 
 
$(document).ready( function(){
    demo_h5_upload_ops.init();
} );

猜你喜欢

转载自blog.csdn.net/adley_app/article/details/87877734