Skip to content

Instantly share code, notes, and snippets.

@tmr232
Created November 8, 2014 14:57
Show Gist options
  • Save tmr232/414bfcfc74398bdac4ab to your computer and use it in GitHub Desktop.
Save tmr232/414bfcfc74398bdac4ab to your computer and use it in GitHub Desktop.
View a file as an image
<html>
<body>
<style>
#byte_content {
margin: 5px 0;
max-height: 100px;
overflow-y: auto;
overflow-x: hidden;
}
#byte_range { margin-top: 5px; }
</style>
<input type="file" id="files" name="file" /> Read bytes:
<span class="readBytesButtons">
<button data-startbyte="0" data-endbyte="4">1-5</button>
<button data-startbyte="5" data-endbyte="14">6-15</button>
<button data-startbyte="6" data-endbyte="7">7-8</button>
<button>entire file</button>
</span>
<div id="byte_range"></div>
<div id="byte_content"></div>
<canvas id="my_canvas" width="400px" height="400px" style="/*width:800px;height:800px;*/"></canvas>
<script>
var canvas = document.getElementById('my_canvas');
var context = canvas.getContext('2d');
function readBlob(opt_startByte, opt_stopByte) {
var files = document.getElementById('files').files;
if (!files.length) {
alert('Please select a file!');
return;
}
var file = files[0];
var start = parseInt(opt_startByte) || 0;
var stop = parseInt(opt_stopByte) || 400*400*4;
var reader = new FileReader();
// If we use onloadend, we need to check the readyState.
reader.onloadend = function(evt) {
if (evt.target.readyState == FileReader.DONE) { // DONE == 2
var image_data = context.createImageData(400, 400);
for (var j = 0,i = 0; i < 400 * 400 * 4; i += 4, j += 8) {
image_data.data[i] = evt.target.result.charCodeAt(j);
image_data.data[i+1] = evt.target.result.charCodeAt(j+1);
image_data.data[i+2] = evt.target.result.charCodeAt(j+3);
image_data.data[i+3] = 255;
}
context.putImageData(image_data, 0, 0);
document.getElementById('byte_range').textContent =
['Read bytes: ', start + 1, ' - ', stop + 1,
' of ', file.size, ' byte file'].join('');
}
};
var blob = file.slice(start, stop + 1);
reader.readAsBinaryString(blob);
}
document.querySelector('.readBytesButtons').addEventListener('click', function(evt) {
if (evt.target.tagName.toLowerCase() == 'button') {
var startByte = evt.target.getAttribute('data-startbyte');
var endByte = evt.target.getAttribute('data-endbyte');
readBlob(startByte, endByte);
}
}, false);
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment