【问题标题】:Javascript ByteBuffer to base64 string not Returning imageJavascript ByteBuffer到base64字符串不返回图像
【发布时间】:2016-06-22 23:20:07
【问题描述】:

在英特尔 XDK 中制作 HTML5 应用程序,因此计算是在 Javascript 中完成的。

案例:从服务器获取 (google) protobuf 消息。将其解析为对象。我们有一张图片,jpg。将其放入 HTML 中。嘿,你可以使用 base64...在那里你可以使用 BitmapFactory:

Bitmap bitmap = android.graphics.BitmapFactory.decodeStream(document.getDocBlob().newInput());

在一些 google-fu 发现这样的东西之后:

var base64String = btoa(String.fromCharCode.apply(null, new Uint8Array(currentComment.Document.doc_blob.buffer)));

var ByteBuffer = ProtoBuf.ByteBuffer;
var base64String = ByteBuffer.btoa(currentComment.Document.doc_blob.buffer, currentComment.Document.doc_blob.littleEndian, currentComment.Document.doc_blob.noAssert);

这是障碍:图片没有显示:它显示了损坏的链接图片。但是使用上述第一个函数时不会引发错误。我认为我出错的地方是偏移量。数据结构如下所示:

buffer: ArrayBuffer
  byteLength: 148199
  __proto__: ArrayBuffer
limit: 69895
littleEndian: true
markedOffset: -1
noAssert: false
offset: 44278
view: DataView

对 HTML 的设置是这样完成的,并且可以正常工作,已经用其他 base64 字符串对其进行了测试:

commentImage = document.getElementById("img-frame"); 
var source = "data:image/" + image_type + ";base64," + base64String;

commentImage.setAttribute("height", currentComment.Document.doc_height);
commentImage.setAttribute("width", currentComment.Document.doc_width);
commentImage.setAttribute("src", source);

【问题讨论】:

    标签: javascript html protocol-buffers intel-xdk protobuf.js


    【解决方案1】:

    这就是我们让它工作的方式:blob 是整个 blob,其中包含图像的起点和终点。

    选项 A:正常 btoa() - 更快

    var base64StringA =  btoa(String.fromCharCode.apply(null, new Uint8Array(currentComment.Document.doc_blob.buffer.slice(currentComment.Document.doc_blob.offset,currentComment.Document.doc_blob.limit))));
    

    选项 B:Bytebuffer.btoa() - 稍微慢一些(但我认为这是一个更安全的选择,因为它不依赖于 btoa() 在窗口中的定义方式,而是依赖于所使用的浏览器...... )

    var base64StringB = ByteBuffer.btoa(String.fromCharCode.apply(null, new Uint8Array(currentComment.Document.doc_blob.buffer.slice(currentComment.Document.doc_blob.offset, currentComment.Document.doc_blob.limit))), currentComment.Document.doc_blob.littleEndian, currentComment.Document.doc_blob.noAssert);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-01-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-09-20
      • 1970-01-01
      • 2023-03-21
      • 1970-01-01
      相关资源
      最近更新 更多