zoukankan      html  css  js  c++  java
  • 图片验证

    根据图片头信息验证

    
        const files = document.getElementById('files')
        const arr = [];
        files.onchange = async function(e) {
          const file = e.target.files;
          arr.push(file[0].slice(0, 6))
          const type = await blobToString(file[0].slice(0, 10))
          console.log(await isJpg(file[0]))
        }
    
        async function isGif(file) {
          // GIF89a 和 GIF87a
          // 前面6个16进制,'47 49 46 38 39 61' '47 49 46 38 37 61'
          const ret = await blobToString(file.slice(0, 6))
          return (ret === '47 49 46 38 39 61' || ret === '47 49 46 38 37 61')
        }
    
        async function isPng(file) {
          const ret = await blobToString(file.slice(0, 8))
          return ret === '89 50 4E 47 0D 0A 1A 0A'
        }
    
        async function isJpg(file) {
          const leng = file.size;
          const start = await blobToString(file.slice(0, 2))
          const end = await blobToString(file.slice(-2, leng))
          return (start === 'FF D8' && end === 'FF D9');
        }
    
        async function isImage(file) {
          // 通过文件流来判断,
          return await isGif(file) || await isPng(file)
        }
    
        function blobToString(blod) {
          return new Promise(resolve => {
            // 读取存储在用户计算机上的文件
            const reader = new FileReader();
            reader.onload = function() {
              const ret = reader.result.split('') // 转换为数组
                .map(v => v.charCodeAt()) // 转换 Unicode 编码 
                .map(v => v.toString(16).toUpperCase()) // 转换为 16进制 在将字符串转换为大写
                .map( v=> v.padStart(2, '0')) // 头部补全
                .join(' ');
              resolve(ret)
            }
            // 开始读取指定的Blob中的内容。一旦完成,result属性中将包含所读取文件的原始二进制数据。
            reader.readAsBinaryString(blod)
          })
        }
    
  • 相关阅读:
    [算法分析]计数排序
    [置顶] 基于stm32f103zet6之UC/OS_II的学习1(初步移植OS点灯大法)
    IOS开发(59)之Block Object的调用
    【译】测试员,敢问路在何方?来自微软工程师
    各种字符串hash
    hdu 2579 BFS
    qq相册
    程序人生之我们的故事:十年如歌(9)
    关联模型和无限极分类
    十大技巧破解电话面试
  • 原文地址:https://www.cnblogs.com/wangyong1997/p/13992910.html
Copyright © 2011-2022 走看看