[HTML5] 拍照上傳圖片完整代碼(for PC)
閒來沒事研究了一個不怎麼實用的功能,終於試出來
環境準備:
自己的PC要有攝影鏡頭,現在的筆電都有附,可以拿自己的筆電玩看看
使用瀏覽器Chrome 18.0.1008以上版本
啟用Media Stream
在網址列輸入chrome://flags/ 啟用Media Stream
必須透過http://瀏覽執行網頁,從檔案總管打開網頁是不會有用的
網頁記得加<!DOCTYPE html>標記,表示這是HTML5網頁
以下是完整代碼:
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<script src="Scripts/jquery-1.4.4.min.js" type="text/javascript"></script>
<video id="myVideo" autoplay="autoplay"></video>
<br />
<input type="button" value="拍照" /><br />
拍照結果:
<div id="result">
</div>
<script type="text/javascript">
$(document).ready(init);
function init() {
//Google Chrome要用webkitGetUserMedia函式
navigator.webkitGetUserMedia("video", success); //顯示影像
//定義button點選後要做什麼
$("input[type='button']").click(function () {
shoot(); //執行拍照
});
}
function success(stream) {
$("#myVideo").attr("src", window.webkitURL.createObjectURL(stream));
}
//執行拍照
function shoot() {
var video = $("#myVideo")[0];
var canvas = capture(video);
$("#result").empty();
$("#result").append(canvas); //呈現圖像(拍照結果)
var imgData = canvas.toDataURL("image/jpg");
var base64String = imgData.substr(22); //取得base64字串
//上傳,儲存圖片
$.ajax({
url: "Handler.ashx",
type: "post",
data: { data: base64String },
async: true,
success: function (htmlVal) {
alert("另存圖片成功!");
}, error: function (e) {
alert(e.responseText); //alert錯誤訊息
}
});
}
//從video元素抓取圖像到canvas
function capture(video) {
var canvas = document.createElement('canvas'); //建立canvas js DOM元素
canvas.width = video.videoWidth;
canvas.height = video.videoHeight;
var ctx = canvas.getContext('2d');
ctx.drawImage(video, 0, 0);
return canvas;
}
</script>
</body>
</html>
(※上傳部份就借用jQuery的$.ajax函式幫忙完成)
Server端處理base64字串的代碼:
<%@ WebHandler Language="C#" Class="Handler" %>
using System;
using System.Web;
using System.Drawing;
using System.IO;
public class Handler : IHttpHandler {
public void ProcessRequest (HttpContext context) {
context.Response.ContentType = "text/plain";
string base64String = context.Request["data"];
Image img = this.Base64ToImage(base64String);
img.Save(@"D:\ccc.jpg");//儲存圖片
}
public bool IsReusable {
get {
return false;
}
}
//把base64字串轉成Image物件
public Image Base64ToImage(string base64String)
{
// Convert Base64 String to byte[]
byte[] imageBytes = Convert.FromBase64String(base64String);
MemoryStream ms = new MemoryStream(imageBytes, 0,
imageBytes.Length);
// Convert byte[] to Image
ms.Write(imageBytes, 0, imageBytes.Length);
Image image = Image.FromStream(ms, true);
return image;
}
}
執行結果:
相關文章: