超清晰!HTML5 实现手机拍照上传功能原理讲解

这篇文章主要为大家详细介绍如何使用HTML5利用摄像头拍照实现上传功能,原理讲解非常清晰,具有较大的参考价值。

超清晰!HTML5 实现手机拍照上传功能原理讲解

上传页面代码:

<style >
    *{
        padding: 0;
        margin: 0;
    }
    .wrapper{
        width: 320px;
        height: 50px;
        margin: 20px auto;
        position: relative;
        border: 1px solid #f0f0f0;
    }
    input{
        width: 100px;
        height: 30px;
    }
    button{
        position: absolute;
        cursor: pointer;
        pointer-events: none;
        width: 100px;
        height: 30px;
        left: 0;
        top: 0;
    }
    a{
        pointer-events: none;
    }
    .img{
        border: 1px solid #ccc;
        padding: 10px;
    }
</style >
 
<div class = "wrapper">
     <input type = "file" accept= "image/*" capture= "camera" id= "img" />
     <button >上传照片 </button >
</div >

上传图片用的HTML5的file文件上传功能<input type=”file” accept=”image/*”>

因为原生file样式不满足要求,在input上面放置我们想要的页面效果。然后当点击上面的元素,就可以触发我们的input进行图片上传。此时的问题是:当点击input上面的元素,需要事件穿透,即相当于点击input。则借助于css3新属性pointer-events。

//使用cursor进行事件穿透,来阻止元素成为鼠标事件的目标
button{
     cursor:pointer;
     pointer-events:none;
}

图片压缩处理

  1. 因为是手机拍照上传,现在的手机拍的照片都很大,如果原图上传,太消耗用户流量,上传前要进行图片压缩。
  2.   通过change事件,监听图片上传,通过readerAsDataURL获取上传的图片。
document.getElementById( 'img').addEventListener( 'change', function () {
     var reader = new FileReader();
     reader.onload = function (e) {
          //调用图片压缩方法:compress();
     };
     reader.readAsDataURL(this.files[0]);
     console.log(this.files[0]);
     var fileSize = Math.round( this.files[0].size/1024/1024) ; //以M为单位
     //this.files[0] 该信息包含:图片的大小,以byte计算 获取size的方法如下:this.files[0].size;
}, false);

 对上传的图片进行压缩,需要借助于canvas API,调用其中的canvas.toDataURL(type, encoderOptions); 将图片按照一定的压缩比进行压缩,得到base64编码。重点来了:压缩策略:先设置图片的最大宽度 or 最大高度,一般设置其中一个就可以了,因为所有的手机宽高比差别不是很大。然后设置图片的最大size,allowMaxSize,根据图片的实际大小和最大允许大小,设置相应的压缩比率。

//最终实现思路:
1、设置压缩后的最大宽度 or 高度;
2、设置压缩比例,根据图片的不同size大小,设置不同的压缩比。
 
function compress(res,fileSize) { //res代表上传的图片,fileSize大小图片的大小
    var img = new Image(),
        maxW = 640; //设置最大宽度
 
    img.onload = function () {
        var cvs = document.createElement( 'canvas'),
            ctx = cvs.getContext( '2d');
 
        if(img.width > maxW) {
            img.height *= maxW / img.width;
            img.width = maxW;
        }
 
        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 compressRate = getCompressRate(1,fileSize);
 
        var dataUrl = cvs.toDataURL( 'image/jpeg', compressRate);
 
        document.body.appendChild(cvs);
        console.log(dataUrl);
    }
 
    img.src = res;
}
 
function getCompressRate(allowMaxSize,fileSize){ //计算压缩比率,size单位为MB
      var compressRate = 1;
 
      if(fileSize/allowMaxSize > 4){
           compressRate = 0.5;
      } else if(fileSize/allowMaxSize >3){
           compressRate = 0.6;
      } else if(fileSize/allowMaxSize >2){
           compressRate = 0.7;
      } else if(fileSize > allowMaxSize){
           compressRate = 0.8;
      } else{
           compressRate = 0.9;
      }
 
      return compressRate;
}

图片上传给服务器

图片已经压缩完成了,但是压缩后的图片不是File,而是一个base64编码,需要以String的形式将base64编码上传给服务器,服务器转存base64为img图片。

125jz网原创文章。发布者:江山如画,转载请注明出处:http://www.125jz.com/10947.html

(1)
江山如画的头像江山如画管理团队
上一篇 2022年8月10日 下午9:14
下一篇 2022年8月11日 上午9:48

99%的人还看了以下文章

  • 第三章 JSP技术1

    了解JSP相关技术
    掌握JSP基本语法
    掌握JSP指令标识和动作标识
    掌握JSP的内置对象及使用

    2018年2月2日
    3.2K0
  • Python编程入门:英文词频统计

    text = “Got tho on super sale. Love it! Cuts my drying time in half Reckon I have had this about a year now,\ at least 7 months. Works great, I use it 5 days a week, blows hot air,…

    2023年10月3日
    5.0K0
  • %matplotlib inline使用详解

    #内嵌画图 %matplotlib inline import matplotlib # 注意这个也要import一次 import matplotlib.pyplot as plt myfont = matplotlib.font_manager.FontProperties(fname=r’C:/Windows/Fonts/msyh.ttf’) # 这一…

    2023年1月13日
    9600
  • 分享一个非常实用的连接数据库javabean

    连接mysql数据库的javabean,修改url数据库连接字符串和驱动程序加载代码,即可成为通用的数据库连接BEAN。 package com.common; import java.sql.*; public class DataBaseConn { public  Connection conn = null; public void createCo…

    2020年12月6日
    2.4K0
  • Pandas读取excel:Excel file format cannot be determined解决方法

    Pandas读取excel时报错,excel表格不能被指定,是什么原因? 这个问题我搞了很久,最后终于搞明白了,网上各种什么utf-8呀,格式化或者另存都不行,我都试过了。 Excel file format cannot be determined解决方法 首先要确定excel已经放在项目目录下,路径是正确的。 一、然后确保安装了所需要的模块 pip in…

    2022年9月11日
    12.2K0
  • python 初学者练手上机实操一

    一、从键盘输入商品名称、商品的单价、商品的数量, 计算商品总价,并按如下格式输出: 商品名称:牛奶,单价:5元,数量:2件,总价:10元 二、从键盘输入年龄,如果>=18岁显示“已成年”,否则显示“未成年”。 三、输入三条边长,如果能构成三角形就计算周长并显示,否则显示“不能构成三角形”。 四、百分制成绩转换为等级制成绩。 要求:如果输入的成绩在90分…

    2023年4月7日
    1.2K0

发表回复

登录后才能评论