开发者

Working With Binary Data in Javascript (Firefox)

I have an image that I've read into a variable in JS (ultimately through the clipboard, if that matters) via the following code.

var rawImg = new Object();
//...populate rawImg (code left out for brevity)

var bis = Components.classes["@mozilla.org/binaryinputstream;1"].createInstance(Components.interfaces.nsIBinaryInputStream);
var is = rawImg.value.QueryInterface(Components.interfaces.nsIInputStream);
bis.setInputStream(is);
var img =  bis.readBytes(is.available());

img is an image. I can verify this using the Base64 library found at http://emilsblog.lerch.org/2009/07/javascript-hacks-using-xhr-to-load.html

var base64Img = Base64.encodeBinary( img );
document.getElementById("holder").innerHTML = '<img src="data:image/png;base64,'+base64Img+'" alt="some image"/>';

This will 开发者_运维百科display the image appropriately. This code is extremely Mozilla-specific and I'm OK with that as my reqs are to support this strictly with FF4+.

My question is two part, a solution to either would be satisfactory. Is it possible to display this image without converting to base64, possibly with the <canvas> tag? Is it possible to transfer this image to the server (XHR or other) as binary without converting to base64?

I could base64.encode(), transfer the string to the server, then decode on the server side but it seems there could be a simpler way.


For your first question, if you had the actual image data (as opposed to the PNG encoding of it), you could just use canvas imagedata. As it is, you will need to do either the base64 thing or create a new protocol handler in which you hand out your input stream in the form of an input stream channel. How well this will work depends on how the code above is called.

For your second question, if you pass an input stream to the send() method of a POST XMLHttpRequest, then the data in the stream will be used as-is as the body of the POST request. The server can just read it from there.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜