新浪微博 登陆  注册   设为首页 加入收藏

学PHP >> HTML5专题 >> 如何使用HTML5实现利用摄像头拍照上传功能

如何使用HTML5实现利用摄像头拍照上传功能

查看次数58902 发表时间2012-12-03 23:23:14

(为便于阅读,对原文进行了不失原意的适当修改,包括代码中一些错误的重复,并作了注释)

  HTML5技术支持WebApp在手机上拍照,显示在页面上并上传到服务器。这是手机微博应用中常见的功能,当然你也可以在其它类型应用中适当使用此技术。

  1、 视频流

  HTML5 的 The Media Capture(媒体捕捉) API 提供了对摄像头的可编程访问,用户可以直接用 getUserMedia (请注意目前仅Chrome和Opera支持)获得摄像头提供的视频流。我们需要做的是添加一个HTML5 的 Video 标签,并将从摄像头获得的视频作为这个标签的输入来源。

  • <video id=”video” autoplay=”"></video>
  • <script>
  • var video_element=document.getElementById(‘video’);
  • if(navigator.getUserMedia){ // opera应使用opera.getUserMedianow
  •       navigator.getUserMedia(‘video’,success,error);  //success是回调函数,当然你也可以直接在此写一个匿名函数
  • }
  • function success(stream){
  •      video_element.src=stream;
  • }
  • </script>
    此时,video 标签内将显示动态的摄像视频流。下面需要进行拍照了。

  2、 拍照

  拍照是采用HTML5的Canvas功能,实时捕获Video标签的内容,因为Video元素可以作为Canvas图像的输入,所以这一点很好实现。主要代码如下:


  • var canvas=document.createElement(‘canvas’); //动态创建画布对象
  • var ctx=canvas.getContext(’2d’);
  • var cw=vw,ch=vh;
  • ctx.fillStyle=”#ffffff”;
  • ctx.fillRect(0,0,cw,ch);
  • ctx.drawImage(video_element,0,0,cw,ch,0,0,vw,vh); //将video对象内指定的区域捕捉绘制到画布上指定的区域,可进行不等大不等位的绘制。
  • document.body.append(canvas);

  3、 图片获取

  从Canvas获取图片数据的核心思路是用canvas的toDataURL将Canvas的数据转换为base64位编码的PNG图像,类似于“data:image/png;base64,xxxxx”的格式。

  • var imgData=canvas.toDataURL(“image/png”);

    这样,imgData变量就存储了一长串的字符数据内容,表示的就是一个PNG图像的base64编码。因为真正的图像数据是base64编码逗号之后的部分,所以要让实际服务器接收的图像数据应该是这部分,我们可以用两种办法来获取。

  第一种:是在前端截取22位以后的字符串作为图像数据,例如:

  • var data=imgData.substr(22);

  如果要在上传前获取图片的大小,可以使用:

  • var length=atob(data).length; //atob 可解码用base-64解码的字串

  第二种:是在后端获取传输的数据后用后台语言截取22位以后的字符串(也就是在前台略过上面这步直接上传)。例如PHP里:

  • $image=base64_decode(str_replace(‘data:image/jpeg;base64,’,”,$data);

  4、 图片上传

  在前端可以使用Ajax将上面获得的图片数据上传到后台脚本。例如使用jQuery时可以用:

  • $.post(‘upload.php’,{‘data’:data});

在后台我们用PHP脚本接收数据并存储为图片。

  • function convert_data($data){
  •      $image=base64_decode(str_replace(‘data:image/jpeg;base64,’,”,$data);
  •      save_to_file($image);
  • }
  • function save_to_file($image){
  •     $fp=fopen($filename,’w');
  •     fwrite($fp,$image);
  •     fclose($fp);
  • }

  以上的解决方案不仅能用于Web App拍照上传,也可以通过Canvas的编辑功能函数提供图片编辑,例如裁剪、上色、涂鸦圈点等功能,然后把用户编辑完的图片上传保存到服务器上。

  在还在不断补充修正的HTML5的驱动下,Web App与Native App之间的距离将越来越小。在可预见的不远的未来,越来越多老的和新的开发项目必将会迁移到WEB应用上来。

相关规范:

The MediaCapture API:http://www.w3.org/TR/media-capture-api/

Canvas:http://dev.w3.org/html5/2dcontext/

 

本文转自:http://h5dev.uc.cn/thread-14-1-1.html 并进行了排版和内容上的一些适当修改。


(转发请注明转自:学PHP)    


  相关推荐



1楼 cheap jordan 12 shoes说: 2015-06-04 01:50:59
Introduce a $100,000 optional medical and rehabilitation benefit along with the existing $1 million optional benefit.. "I know she will be with us every step of the way in our hearts and will continue to inspire us every single day.". They apparently had the goods on these people prior to the elections which could have been a major game changer in this regard.
2楼 retro jordan 3 for sale说: 2015-06-04 18:39:03
The film becomes a surreal and nihilistic work that which is incomprehensible to the white protagonists, namely Africa, is portrayed as sinister and irrational. A large part of our recent success in Harrison has been the ability to focus time and energy in moving in the same direction.
3楼 air jordan 4 cavs for sale说: 2015-06-13 06:47:19
"We sat at a big farmer's table and passed the plates from one person to the next. At that time, Roseburg was the capital of the United States, because more board feet of harvested timber from Forest Service land ended up being cut in the seven mills in my hometown and smaller mills of Douglas County than anywhere else.
4楼 fire red 5s for sale说: 2015-06-25 05:48:23
Along with Dyson's bagless Root Cyclone technology, which spins debris out of the air and into the storage bin, the cordless vac deploys a digital motor that cranks at 104,000 rpm for maximum suction. A motorized head uses carbon fiber filaments to capture fine dust particles, and a lightweight aluminum wand reaches ceilings and fans.
5楼 jordan low 11s说: 2015-06-25 06:15:09
Legislation providing $900m for IT security research and education to protect against hackers and terrorists has been signed by President Bush. Under the Cyber Security Research and Development Act, computer security research centres and educational fellowships will be set up at the National Science Foundation and the National Institute of Standards and Technology (NIST).
6楼 toms Sko说: 2015-06-25 23:22:43
This year they have more of them."It not so much more families as families with children I think is what the main situation is for us," Gilmore says.Gilmore says they still have the same number of donors as previous years, but are in need of more to help out those extra children."Our donors are still there, that they can do quite as much as they have been able to do in the past. I think it the economy.
7楼 air jordan retro 6 for sale说: 2015-06-27 02:26:34
I just expected her to use her voice her blog at the very least or a PSA to speak out against the measure. She does not live in California, but this amendment have national implications and she should well know that.. The agency Coke sued claimed it would suffer "tremendous and unsustainable losses" if made to pay overtime. But such claims are belied by the fact that home care employers have managed to stay in business and are profitable in the 21 states that already mandate minimum wage or overtime pay, with no reported decline in the amount or the quality of care provided..This keeps happening despite the fact that the VA spends an average of $5,000 per patient, vs. The national average of $6,300.. She says she became concerned after seeing some of the texts the coachThe mom, who preferred to remain unidentified to protect her daughter, said the coach asked her daughter for her cell phone number.Woman victim of identity theft at Jackson hotelWoman victim of identity theft at Jackson hotelUpdated: Friday, September 19 2014 12:44 AM EDT2014 09 19 04:44:47 GMTPolice are investigating a case of debit card fraud inside a Jackson hotel room. The victim said her personal information is being held hostage by someone who had access to her room.On Sept.
8楼 Toms Sko说: 2015-06-27 07:27:26
Formerly the urban district of Whitley and Monkseaton, Whitley Bay was chartered as a municipal borough in 1954. .But the pair, who had been boozing on vodka, were thrown out bydoormen after an altercation inside the club, North Shields Coordinates:North Shields (or locally just Shields) is a town on the north bank of the River Tyne, in the metropolitan borough of North Tyneside, in North East England.
9楼 where to buy jordan 3说: 2015-06-29 10:09:31
Frozen in My TracksI remained standing where I was for a minute or so but heard and saw nothing more, so I decided to continue with my intended mission. I took a couple more steps inside and reached the first set of built in shelving. It seems the only time funding is called for is after a tragedy like Aurora. The existing facilities have been forced to take on increasingly needy populations, beyond what thy were designed for.These shortsighted and ineffective policies not only seem bad for the tax payer, but also exact a human toll which cannot be quantified. So, once again Tami asks, a nursing home really the appropriate place for me?. SEATTLE (AP) Washington's Supreme Court on Thursday narrowly upheld a $57 million verdict against the state in a case brought by workers who care for severely disabled people. But the justices declined to give the workers pre judgment interest throwing out an additional $39 million awarded by a lower court judge..
10楼 jordan xx8说: 2015-06-29 10:36:09
Just recently we were able to open up two of those six, so now there's only four closed."While there are four (palliative) beds closed, one can look at it in a positive way that there are two fewer closed than there was not very long ago," he said.Dewar said recently, because of staffing issues, the three intermediate ICU beds were temporarily closed."We're trying different ways to get them staffed," he said."The way we look at it is it hasn't impacted our ability to provide service. While it is preferable to have those intermediate beds for transition from ICU to the medical or surgical units, now they go directly back to the unit.
11楼 Jordan 6 Low Infrared 23 for sale说: 2015-06-30 06:10:59
We have a corrupt system. My main contention is that climate change will direct our future, and will determine whether we even exist as a species. The arrival of give it away competition in any market immediately lowers the value of private investments already made and chills new investment the private money knows it can't compete with federal tooth fairies over the long term. The vendors of equipment and services will of course scramble to sell their wares to the tooth fairy instead.
12楼 Toms norge salg说: 2015-07-01 02:19:52
Officials say it will broadly answer some of those questions, although probably not in detail.Further evidence of the improving investigations is the increase in cyber related arrests.According to the FBI, there were 202 arrests on cyber cases in 2010, compared to 159 the previous year. And a number of those were high profile, multimillion dollar breaches involving investigations that spanned several countries and foreign enforcement agencies.
13楼 toms sko norge说: 2015-07-04 00:01:21
beklage at vi fjerner det saftige gresset deres, men vi gj酶r bare jobben v氓r p氓 bestilling fra
14楼 Toms说: 2015-07-05 19:44:43
av disse tre m氓lene, nei takk.
15楼 Toms说: 2015-07-07 01:39:10
endringa i hele menneskehetens historie. Men hva for氓rsaka denne endringa? Og hvorfor i all verden
16楼 Toms Sko说: 2015-07-08 20:28:10
insured. That's for when you go back home. She also has osteoporosis, which is worsening the pain..
17楼 Toms Sko说: 2015-07-12 16:36:25
It hard to describe the feeling, it like numbness but not the needle kind.. The Haverhill police
18楼 魔兽世界欧服金币说: 2015-12-04 23:58:40
我经常在www.pls173.com网站买魔兽世界欧服代练,服务态度好,代练基本上是立即就开始了,金币发货快,秒发。下次买嗨来这里。
19楼 -1'说: 2016-02-19 01:30:41
1
20楼 -1'说: 2016-03-31 08:45:17
1
21楼 学phper说: 2016-04-17 02:26:50
1
22楼 -1'说: 2016-04-17 02:26:52
1
23楼 Maralynn说: 2016-09-09 14:28:55
where to buy canada goose 4color printing has somewhat revolutionized the printing industry since it has made color jobs easy and affordable. michael kors totes hywidwmdxvyfvfnk canada goose on sale fvvniang christian louboutin shoe sale lqwwjtnv Abercrombie &amp; Fitch
24楼 Rusty说: 2016-12-22 01:14:01
If you're looking to buy these artilces make it way easier.
25楼 Rusty说: 2016-12-22 01:14:43
If you're looking to buy these artilces make it way easier.
26楼 学phper说: 2017-01-26 10:38:56
1
27楼 -1'说: 2017-01-26 10:38:57
1
28楼 Lashonda说: 2018-02-19 04:20:15
download windows 910 me upgrade to windows 10 discount windows 10 download

  发表评论
昵称:
(不超过20个字符或10个汉字)
内容: