1. 程式人生 > >基於html5、JS實現的拍照上傳圖片

基於html5、JS實現的拍照上傳圖片

原理:調出攝像頭,拍照儲存到畫布,將圖片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); }
        }
    }
}

效果如下圖: