Getting binary representation of an image file
suggest changeThis example is inspired by this question.
We’ll assume you know how to load a file using the File API.
// preliminary code to handle getting local file and finally printing to console
// the results of our function ArrayBufferToBinary().
var file; // handle for the local file
var reader = new FileReader();
reader.onload = function(event) {
var data = event.target.result;
console.log(ArrayBufferToBinary(data));
};
reader.readAsArrayBuffer(file); //gets an ArrayBuffer of the file
Now we perform the actual conversion of the file data into 1’s and 0’s using a DataView:
function ArrayBufferToBinary(buffer) {
// Convert an array buffer to a string bit-representation: 0 1 1 0 0 0...
const dataView = new DataView(buffer);
let response = "", offset = (8/8);
for(let i = 0; i < dataView.byteLength; i += offset) {
response += dataView.getUint8(i).toString(2).padStart(8, "0");
}
return response;
}
DataViews let you read and write numeric data. getUint8 reads the byte at the given offset as an unsigned 8-bit integer. toString(2) turns that integer into binary, and padStart keeps each byte eight characters wide. getInt8 is the wrong choice here: bytes from 128 through 255 become negative, and (-1).toString(2) is "-1", not "11111111". Without padding, a zero byte becomes "0" and the bits from neighboring bytes run together.
Files are saved as bytes. The offset is 1 because each step reads one 8-bit integer. Reading the same bytes as 32-bit integers would use an offset of 32 / 8, which is 4.
For this task, DataView is more than you need. It is useful when endianness or mixed numeric fields matter, for example when a file header stores different widths. A textual dump of each byte does not need that.
A shorter solution uses a Uint8Array, which views the whole ArrayBuffer as unsigned 8-bit integers:
function ArrayBufferToBinary(buffer) {
const uint8 = new Uint8Array(buffer);
return uint8.reduce((binary, byte) => binary + byte.toString(2).padStart(8, "0"), "");
}