APP的H5页面实现图片预览及压缩上传

导语

本篇文章使用H5实现图片预览,压缩上传的功能,主要用到了以下知识点。

  • 使用<input type="file" accept="image/*" >获取上传的图片文件
  • 使用H5 FileReader 上传。通FileReader API读取本地的图片文件,然后将文件转换成base64编码的字符串,即Data URL。
  • 使用canvas的toDataURL方法,设置图片质量,来压缩图片
  • 使用exif.js来解决ios手机上传竖拍照片会逆时针旋转90度,横拍照片无此问题(Android手机没有这个问题)

开始实现

1、HTML代码
<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <meta http-equiv="x-ua-compatible" content="IE=edge,chrome=1">
    <meta name="renderer" content="webkit">
    <meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta name="format-detection" content="telephone=no"> <!-- 解决浏览器自动显示手机号问题 -->
    <meta name="apple-touch-fullscreen" content="yes">
    <meta name="apple-mobile-web-app-capable" content="yes">
    <meta name="apple-mobile-web-app-status-bar-style" content="black">
    <meta name="format-detection" content="telephone=no" />
    <title>H5图片上传</title>
</head>
<body>
     <div class="loadFP">
         <div>
           <img src="~/img/cameraPic.png" alt="" id="ImgFront">
         </div>
        <form id="uploadFrontFrom" enctype="multipart/from-data">
           <input type="file"  accept="image/*" id="uploadFrontInput">
        </form>
        <div >点击上传身份证正面</div>
    </div>
    <div class="loadBP">
        <div>
          <img src="~/img/cameraPic.png" alt="" id="ImgBack">
        </div>
        <form id="uploadBackFrom" enctype="multipart/from-data">
          <input type="file"  accept="image/*" id="uploadBKInput">
        </form>
        <div >点击上传身份证反面</div>
    </div>
    <div class="Footer">
        <input type="button" value="提交"  id="loadImg" disabled="disabled">
    </div>
    <script src="~/scripts/jquery-1.8.2.min.js"></script>
    <script src="~/scripts/exif.js"></script>
    <script src="~/scripts/uploadPic.js"></script>
</body>
</html>

2、JS代码实现
var isFront = false;
var frontUri = "";
var bkUri = "";
//图片方向角
var Orientation = null;
$("#uploadBKInput").on("change", function () {
    var file = this.files[0];
    isFront = false;
    fileReader(file, isFront);
})
$("#uploadFrontInput").on("change", function () {
    var file = this.files[0];
    isFront = true;
    fileReader(file, isFront);
})
var uploadMaxSize = 5 * 1024 * 1024;
var imgSize = 3 * 1024 * 1024;
function fileReader(file, isFront) {
    if (typeof FileReader == "undefined") {
        return false;
    }
    if (file == undefined) { return; }
    if (file.size == 0) { return; }
    if (file.size > uploadMaxSize) {
        console.log( "您上传的图片大于5M,请重新上传");
        return;
    }
    if (!/(jpg|jpeg|png|bmp|JPG|PNG|BMP)$/.test(file.type)) { return false; }
    //获取照片方向角属性,用户旋转控制
    EXIF.getData(file, function () {
        EXIF.getAllTags(this);
        Orientation = EXIF.getTag(this, "Orientation");
    })

    var oReader = new FileReader();
    oReader.onload = function (e) {
        var img = new Image();
        img.src = e.target.result;
        img.onload = function () {
            var degree = 0, drawWidth, drawHeight, width, height;
            drawWidth = this.width;
            drawHeight = this.height;
            //以下改变一下图片大小
            var maxSide = Math.max(drawWidth, drawHeight);
            if (maxSide > 1024) {
                var minSide = Math.min(drawWidth, drawHeight);
                minSide = minSide / maxSide * 1024;
                maxSide = 1024;
                if (drawWidth > drawHeight) {
                    drawWidth = maxSide;
                    drawHeight = minSide;
                } else {
                    drawWidth = minSide;
                    drawHeight = maxSide;
                }
            }
            var canvas = document.createElement('canvas');
            canvas.width = width = drawWidth;
            canvas.height = height = drawHeight;
            var context = canvas.getContext('2d');
            //判断图片方向,重置canvas大小,确定旋转角度,iphone默认的是home键在右方的横屏拍摄方式
            if (Orientation != "" && Orientation != 1 && Orientation != undefined) {
                switch (Orientation) {
                    //iphone横屏拍摄,此时home键在左侧
                    case 3:
                        degree = 180;
                        drawWidth = -width;
                        drawHeight = -height;
                        break;
                        //iphone竖屏拍摄,此时home键在下方(正常拿手机的方向)
                    case 6:
                        canvas.width = height;
                        canvas.height = width;
                        degree = 90;
                        drawWidth = width;
                        drawHeight = -height;
                        break;
                        //iphone竖屏拍摄,此时home键在上方
                    case 8:
                        canvas.width = height;
                        canvas.height = width;
                        degree = 270;
                        drawWidth = -width;
                        drawHeight = height;
                        break;
                }
            }
            //使用canvas旋转校正
            context.rotate(degree * Math.PI / 180);
            context.drawImage(img, 0, 0, drawWidth, drawHeight);
            // 压缩0.5就是压缩百分之50
            var data = canvas.toDataURL('image/jpeg', 0.5);
            if (file.size > imgSize) {
                data = canvas.toDataURL('image/jpeg', 0.7);
            }
            canvas = context = null;
            if (!isFront) {
                bkUri = data;
                $("#ImgBack").attr("src", data);
            } else {
                frontUri = data;
                $("#ImgFront").attr("src", data);
            }
            if (frontUri != "" && bkUri != "") {
                $("#loadImg").removeClass("disabled");
            }
        }
    };
    oReader.readAsDataURL(file);
}

$("#loadImg").click(function () {
    if (frontUri == "" || bkUri == "") { return; }
    $.ajax({
        url:  "uploadImg",
        data: { "ImgB": + bkUri.split(",")[1] ,"ImgA": + frontUri.split(",")[1]  },
        dataType: "json",
        type: "post",
        success: function (json) {
            if (json.Code == "true") {
                alert("图片上传成功");
            } else {
                alert("上传失败,请重新上传");
            }
        },
        error: function () {
            alert("出错了!");
        }
    })
})
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容