H5上传图片之canvas

Posted 智者乐水 仁者乐山 吾者乐进

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了H5上传图片之canvas相关的知识,希望对你有一定的参考价值。

H5上传图片之canvas,使用canvas处理压缩图片再上传

html代码:

<form action="" method="post">
    <dl>
        <dd>
            <div>
                <div id="img_wrap">

                </div>
                <input type="file" accept="image/jpg,image/jpeg,image/png,image/gif" id="fileImage" multiple="multiple" name="img" style="display:none" />
                <a id="upimg" href="javascript:">上传图片</a>
            </div>
        </dd>
        <dd style="margin-top:10px;">
            <a id="abtn_submit" href="javascript:">提交</a>
        </dd>
    </dl>
</form>

js代码:

<script type="text/javascript">
    $(function () {
        $("#abtn_submit").click(function () {
            if ($("input[name=‘imgs‘]").length < 1) {
                layer.open({
                    content: ‘必须上传图片才能提交‘,
                    skin: ‘msg‘,
                    time: 2
                });
                return;
            }
            $("form").submit();
        });
        $("#upimg").click(function () {
            $("#fileImage").click();
        })
        $("#fileImage").change(function () {
            $.each($(this)[0].files, function (i, e) {
                if (!/image\/\w+/.test(e.type)) {
                    //请确保文件为图像类型
                    return;
                }
                imgHandle(e);
            })
        })
    });

    function imgHandle(_file) {
        var reader = new FileReader();
        reader.readAsDataURL(_file);
        reader.onload = function (e) {
            var result = e.target.result;
            var image = new Image();
            image.src = result;
            image.onload = function () {
                var cvs = document.createElement("canvas");
                var scale = 1;
                if (this.width > 1000 || this.height > 1000) {
                    if (this.width > this.height) {
                        scale = 1000 / this.width;
                    }
                    else {
                        scale = 1000 / this.height;
                    }
                }
                cvs.width = this.width * scale;
                cvs.height = this.height * scale;
                var ctx = cvs.getContext("2d");
                ctx.drawImage(this, 0, 0, cvs.width, cvs.height);
                var newImageData = cvs.toDataURL(_file.type, 0.8);
                var imgdata = "<a href=‘javascript:‘ onclick=‘delimg(this)‘><img src=\"" + newImageData + "\" />";
                imgdata += "<input type=\"hidden\" name=\"imgs\" value=\"" + newImageData + "\" /></a>";
                $("#img_wrap").append(imgdata);
            }
        }
    }

    function delimg(e) {
        layer.open({
            content: ‘您确定要删除此图片吗?‘,
            btn: [‘删除‘, ‘取消‘],
            skin: ‘footer‘,
            yes: function (index) {
                $(e).remove();
                layer.close(index);
            }
        });
    }
</script>

  后台处理代码:

//有图片时处理如下
            string[] imgs = collection.GetValues("imgs");
            List<U_Img> uimglist = new List<U_Img>();
            int i = 1;
            foreach (string imgBase64Str in imgs)
            {
                int indexOf = imgBase64Str.IndexOf(‘/‘) + 1;
                string ftype = imgBase64Str.Substring(indexOf, imgBase64Str.IndexOf(‘;‘) - indexOf);
                string fex = ".jpg";
                switch (ftype)
                {
                    case "jpeg":
                    case "jpg":
                        fex = ".jpg";
                        break;
                    case "png":
                        fex = ".png";
                        break;
                    case "gif":
                        fex = ".gif";
                        break;
                }
                string Base64Str = imgBase64Str.Substring(imgBase64Str.IndexOf(‘,‘) + 1);
                Base64Str = Base64Str.Trim(‘\0‘);
                byte[] imgArr = Convert.FromBase64String(Base64Str);
                using (MemoryStream ms = new MemoryStream(imgArr))
                {
                    Bitmap bmp = new Bitmap(ms);
                    string fname = "/timg/" + DateTime.Now.ToString("yyMMddmmHHssffff") + i.ToString() + fex;
                    string FilePath = Request.MapPath(fname);
                    bmp.Save(FilePath);
                    uimglist.Add(new U_Img() { ImgUrl = fname, ImgTime = DateTime.Now });
                }
                i++;
            }

  

 

以上是关于H5上传图片之canvas的主要内容,如果未能解决你的问题,请参考以下文章

APICloud开发者进阶之路| JS利用H5的canvas操作微信浏览器上传图片方向旋转

前端预览图片和H5canvas压缩图片上传

H5压缩图片上传(FileReader +canvas)

## H5 canvas画图白板踩坑

## H5 canvas画图白板踩坑

H5相机上传图片压缩