【发布时间】:2014-11-08 14:10:54
【问题描述】:
我们正在使用 websocket 来传输 bytearray 中的数据。在接收端,javascript 必须确定接收到的 ArrayBuffer 是 String 类型还是 Image 类型。如果是字符串,则转换为字符串,否则转换为 Blob。如下所示,除了我不知道如何识别 arraybuffer 是字符串或图像。
if (message instanceof ArrayBuffer) {
if(message of type string)
var bytearray = new Uint8Array(message);
to convert to string
var out = String.fromCharCode.apply(null, bytearray);
console.log(out);
}
if(message of type image){
imageId.height = 400;
imageId.width = 600;
imageId.src = convertArrayBufferBlobUrl(message);
}
更新:
我将从服务器发送图像作为以下 java 代码。我如何在字节数组中附加或前置标志以被客户端浏览器(javascript)识别为图像或字符串?
ImageIO.write(getSubImage(bufferedImage,width,height), "png", baos); byte[] 结果=baos.toByteArray();
【问题讨论】:
-
图片是什么格式的?
-
您需要将文件名、mime 类型等元数据与数据一起发送。
-
你能给我发个例子吗?
-
即使不发送 mime 类型,您也可以将魔法/签名用于图像类型 en.wikipedia.org/wiki/List_of_file_signatures
-
Websocket 通常使用 HTTP 作为底层传输层。因此,可以使用主要消息将 HTTP 标头附加到 HTTP 正文。方式服务器可以设置
Content-Type,cookie或者你自己自定义的header。通常Content-Type(具有image/png或text/plain之类的值)就足够了,如果不是,那么自定义标头可以解决所有问题。您需要在服务器和客户端上使用的确切 API 主要取决于您使用的库。
标签: javascript image blob arraybuffer