使用 IndexedDB 数据库 存储图片

使用 IndexedDB 数据库 存储图片

  • Indexed_db.js
// 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})
}

猜你喜欢

转载自www.cnblogs.com/zhang-zi-yi/p/12703656.html
今日推荐