使用 IndexedDB 數據庫 存儲圖片
// IndexedDB
var indexedDB = window.indexedDB || window.webkitIndexedDB || window.mozIndexedDB || window.OIndexedDB || window.msIndexedDB,
IDBTransaction = window.IDBTransaction || window.webkitIDBTransaction || window.OIDBTransaction || window.msIDBTransaction,
dbVersion = 2
if(!indexedDB) {
console.log("你的瀏覽器不支持IndexedDB");
}
// 打開數據庫
var request = indexedDB.open('ImagesDB', dbVersion)
, DB
request.onerror = function (e) {
// 數據庫打開失敗
console.log(e.currentTarget.error.message)
}
request.onupgradeneeded = function (e) {
DB = e.target.result
if (!DB.objectStoreNames.contains('VideoImages')) {
//如果表格不存在,創建一個新的表格
// (keyPath,主鍵 ; autoIncrement,是否自增),會返回一個對象(objectStore)
var objectStore = DB.createObjectStore('VideoImages') // , { keyPath: 'id', autoIncrement: true }
// 指定可以被索引的字段,unique字段是否唯一
// objectStore.createIndex('fileName', 'name', { unique: false })
}
}
request.onsuccess = function (event) {
// 數據庫打開成功
DB = request.result
DB.onerror = function (e) {
console.log(e.currentTarget.error.message)
}
}
function putImageInDb (blob, key) {
// 將blob 對象存儲到數據庫中
var transaction = DB.transaction(['VideoImages'], 'readwrite')
var put = transaction.objectStore('VideoImages').put(blob, key)
}
function getImageRequest (key) {
// 獲取圖片文件
var transaction = DB.transaction(['VideoImages'], 'readwrite')
transaction.objectStore('VideoImages').get(key).onsuccess = (event) => {
// 異步回調
let blob = event.target.result
if (blob) {
var url = window.URL.createObjectURL(blob)
$('.img').attr('src', url)
}
}
}
video 視頻截圖 並轉換為 Blob 對象
function savePic (fileName, fileType) {
if (!fileType) fileType = 'png' // 默認使用png
var video = document.querySelector('#cameraVideo') // 找到需要截圖的video標簽
var canvas = window.canvas = document.createElement('canvas')
canvas.width = video.videoWidth
canvas.height = video.videoHeight
// 圖片大小和視頻分辨率一致
canvas.getContext('2d').drawImage(video, 0, 0, canvas.width, canvas.height)
// canvas中video中取一幀圖片並轉成dataURL
var strDataURL = canvas.toDataURL('image/' + fileType)
var arr = strDataURL.split(','),
mime = arr[0].match(/:(.*?);/)[1],
bstr = atob(arr[1]),
n = bstr.length,
u8arr = new Uint8Array(n)
while (n--) {
u8arr[n] = bstr.charCodeAt(n)
}
// 返回 Blob 對象
return new Blob([u8arr], {type: mime})
}