zoukankan      html  css  js  c++  java
  • 接收二进制流(ArrayBuffer) ,并且显示二进制流图片

    1.调用接口,返回二进制流数据

    var xhr = new XMLHttpRequest();
        xhr.onreadystatechange = function() {
            if (xhr.readyState == 4 && xhr.status == 200) {//
                var responseText = xhr.responseText;
                //返回二进制数据流
                console.log(responseText);
            }
        };
        xhr.open("GET", "/getData", true);
    //需要设置
    responseType
      xhr.responseType = "arraybuffer";
      xhr.send(null)

    2. 把二进制数据转为base64

     function arrayBufferToBase64(buffer) {
            var binary = '';
            var bytes = new Uint8Array(buffer);
            var len = bytes.byteLength;
            for (var i = 0; i < len; i++) {
                binary += String.fromCharCode(bytes[i]);
            }
            return window.btoa(binary);
        }

    3.显示图片

    var response = xhr.response;
               var url= arrayBufferToBase64(response);
               document.getElementById('img').src='data:image/jpeg;base64,'+url;

    完整代码

    var xhr = new XMLHttpRequest();
        xhr.open("GET", "/getdata", true);
        xhr.responseType = "arraybuffer";
        xhr.send(null);
        xhr.onreadystatechange = function() {
            if (xhr.readyState == 4 && xhr.status == 200) {
                //二进制数据流
                var response = xhr.response;
                var url= arrayBufferToBase64(response);
                document.getElementById('img').src='data:image/jpeg;base64,'+url;
            }
        };
       function arrayBufferToBase64(buffer) {
            var binary = '';
            var bytes = new Uint8Array(buffer);
            var len = bytes.byteLength;
            for (var i = 0; i < len; i++) {
                binary += String.fromCharCode(bytes[i]);
            }
            return window.btoa(binary);
        }
    View Code
  • 相关阅读:
    11.变分推断
    10.高斯混合模型GMM
    9.EM 算法
    8.指数族分布
    7.概率图模型(表示/推断/学习)
    6.核方法
    二分查找
    2.3 数据结构---数组(连续)
    C#开发Windows服务的基础代码
    C#与C++之间类型的对应{转}
  • 原文地址:https://www.cnblogs.com/heihei-haha/p/9209648.html
Copyright © 2011-2022 走看看