基于html5、JS实现的拍照上传图片

本文介绍了一个使用HTML5和JavaScript实现的前端拍照功能,并通过Ajax将照片上传至服务器的方法。前端利用getUserMedia API调用摄像头,将拍摄的照片绘制到Canvas元素上,再将其转化为Base64编码的数据发送到后台。后台采用C#处理接收到的数据并保存为图片。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

原理:调出摄像头,拍照保存到画布,将图片URi传送到后台


前端代码(Index.cshtml):

<style>
#video,#canvas {display: block;margin:1em auto;width:180px;height:180px;}
#snap { display: block;margin:0 auto;width:80%;height:2em; }
</style>
<div class="container">  
    <video id="video" autoplay></video>       
    <button id="snap">点击拍照</button>        
    <canvas id="canvas"></canvas> 
</div>
<script>
    window.addEventListener("DOMContentLoaded", function () {
        try { document.createElement("canvas").getContext("2d"); } catch (e) { alert("not support canvas!") }
        var video = document.getElementById("video"),
            canvas = document.getElementById("canvas"),
            context = canvas.getContext("2d");
            navigator.getUserMedia = navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia || navigator.msGetUserMedia;

        if (navigator.getUserMedia)
            navigator.getUserMedia(
                { "video": true },
                function (stream) {
                    if (video.mozSrcObject !== undefined)video.mozSrcObject = stream;
                    else video.src = ((window.URL || window.webkitURL || window.mozURL || window.msURL) && window.URL.createObjectURL(stream)) || stream;               
                    video.play();
                },
                function (error) {
                    //if(error.PERMISSION_DENIED)console.log("用户拒绝了浏览器请求媒体的权限",error.code);
                    //if(error.NOT_SUPPORTED_ERROR)console.log("当前浏览器不支持拍照功能",error.code);
                    //if(error.MANDATORY_UNSATISFIED_ERROR)console.log("指定的媒体类型未接收到媒体流",error.code);
                    alert("Video capture error: " + error.code);
                }
            );
        else alert("Native device media streaming (getUserMedia) not supported in this browser");
       
        $('#snap').on('click', function () {
            context.drawImage(video, 0, 0, canvas.width = video.videoWidth, canvas.height = video.videoHeight);
            $.post('/home/index', { "img": canvas.toDataURL().substr(22) }, function (data, status) {
                alert(status!="success"?"图片处理出错!":data== "yes"?"图片上传完成!":data);           
            }, "text");
        });
    }, false);
 </script> 

后台代码(HomeController.cs):

using System;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Web.Mvc;

namespace WebFrame.Controllers
{
    public class HomeController : Controller
    {
        public ActionResult Index() { return View(); }

        [HttpPost]
        public ActionResult Index(FormCollection form)
        {
            try
            {
                byte[] imgBytes = Convert.FromBase64String(form["img"]);
                Stream stream = new MemoryStream(imgBytes);
                Image imgae = Image.FromStream(stream);
                imgae.Save(HttpContext.Server.MapPath("~/") + Guid.NewGuid().ToString() + ".jpg", ImageFormat.Jpeg);
                return Content("yes");
            }
            catch (Exception e) { return Content(e.Message); }
        }
    }
}


效果如下图:




附上Demo下载地址:  基于html5、JS实现的拍照上传图片(免积分)


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值