zoukankan      html  css  js  c++  java
  • [JavaScript]使用ArrayBuffer和Blob编辑二进制流

    Blob()构造方法返回一个新的Blob对象. 内容是包含参数array的二进制字节流.

    语法

    var aBlob = new Blob( array, options );
    

    参数

    • array is an Array of ArrayBuffer, ArrayBufferView, Blob, DOMString objects, or a mix of any of such objects, that will be put inside the Blob. DOMStrings are encoded as UTF-8.
    • options is an optional BlobPropertyBag dictionary which may specify the following two attributes:
      • type, with a default value of "", that represents the MIME type of the content of the array that will be put in the blob.
      • endings, with a default value of "transparent", that specifies how strings containing the line ending character are to be written out. It is one of the two values: "native", meaning that line ending characters are changed to match host OS filesystem convention, or "transparent", meaning that endings are stored in the blob without change.
    var buffer = new ArrayBuffer(2);
    var int8View = new Int8Array(buffer);
    int8View[0] = 170;
    int8View[1] = 254;
    
    var blob = new Blob([int8View, event.target.result]);
    

     此段代码创建了一个2字节的二进制数10101010和11111110,并且把它追加到了event.target.result字节流的头部

    var buffer = new ArrayBuffer(8);
    var uInt32 = new Uint32Array(buffer);
    uInt32[0]  = 2356021;
    
    console.log(uInt32[0]); // 2356021
    console.log(uInt32.length); // 2
    console.log(uInt32.BYTES_PER_ELEMENT); // 4
    
    var view = new DataView(buffer,0,8);
    console.log(view.getUint32(0,4));//2356021

    此段代码创建了2个无符号32位整数buff(一个unsigned int需要4个字节空间,所以new ArrayBuffer(8)分配了8个字节,即,可容纳8/4=2个unsigned int类型的整数);

    在第1个数组放置2356021,当然你可以使用uInt32[1]放置第二个值,但是你只能放置2个值,毕竟它只分配了8/4=2个unsigned int类型的整数;

    调用length可查看ArrayBuffer的长度,这里是2,调用BYTES_PER_ELEMENT可查看每个元素占用的字节数,这里是4;

    运用DataView可以以一种方式去读取某段buff的值;

     查看更多的例子:

    运用XHR异步请求接收二进制流

  • 相关阅读:
    迭代器和生成器
    python装饰器详述
    python爬虫-Response对象的属性
    python爬虫入门-开发环境与小例子
    c语言贪吃蛇详解5.GameOver功能与显示成绩
    c语言贪吃蛇详解4.食物的投放与蛇的变长
    vb实验7-找出小于18000的最大素数
    qt学习教程1.qt开发环境搭建
    链栈类模板实现
    顺序栈类模板实现
  • 原文地址:https://www.cnblogs.com/yiyide266/p/6351446.html
Copyright © 2011-2022 走看看