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++; }