12

Say I had a URL like

http://my.website.com/myfile.raw

and this file it points to was just raw bytes, representing an intensity image. Is it possible to grab this data and read the bytes in JavaScript? And then using it with HTML5 canvas (e.g. putImageData) to draw an image?

Or is there some other way to do this in the browser without Java or Flash?

Qantas 94 Heavy
  • 15,750
  • 31
  • 68
  • 83
whiskeyspider
  • 121
  • 1
  • 3

2 Answers2

1

maybe

function draw() {
    var ctx = document.getElementById('canvas').getContext('2d');
    var img = new Image();
    img.onload = function(){
      ctx.drawImage(img,0,0);
      imageData = ctx.getImageData(0, 0, image.width, image.height)
      //now you can do something with imageData...
    }
    img.src = 'http://my.website.com/myfile.raw';
  }
Drew LeSueur
  • 19,185
  • 29
  • 89
  • 106
  • Does this really work? Normally the `src` attribute references a file in a known format such as png or jpg. I don't think browsers know about a "raw" format... – antinome Jun 29 '14 at 01:46
  • I think I misread the question when I answered that 4 years ago. Sorry. – Drew LeSueur Aug 25 '14 at 21:40
  • I would maybe use this: https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/Sending_and_Receiving_Binary_Data or even binary data with Websockets. Then you can do what ever you want with the data -- draw it to canvas etc. – Drew LeSueur Aug 25 '14 at 21:47
0
<head>
<title>foo</title>
<script>
var canvas;

function draw(imgData) {
    var ctx = canvas.getContext('2d');
    var myImageData = ctx.createImageData(canvas.width, canvas.height);
    var ctxData = myImageData.data
    var iter = canvas.width * canvas.height * 4; //RGBA
    while(iter--){ctxData[iter] = imgData[iter];}
    ctx.putImageData(myImageData, 0, 0);
}

function httpGetAsync(theUrl, callback) {
    var xmlHttp = new XMLHttpRequest(); 
    xmlHttp.responseType = "arraybuffer";   
    xmlHttp.onreadystatechange = function() { 
        if (xmlHttp.readyState == 4 && xmlHttp.status == 200){
            var arrayBuffer = xmlHttp.response
            var byteArray = new Uint8Array(arrayBuffer);
            callback(byteArray);
        }
    }
    xmlHttp.open("GET", theUrl, true); // true for asynchronous 
    xmlHttp.send(null);
}

function tick(){
    httpGetAsync("http://127.0.0.1:8082/video", draw);
}

function loaded(){
    canvas = document.getElementById('canvas');
}

window.setInterval(tick, 10000);
window.onload = loaded;

</script>
</head>
<body>
    <div>.................</div>
    <canvas id='canvas' width="320" Height="240" ></canvas>
    <div>.................</div>
</body>
andrew pate
  • 3,833
  • 36
  • 28