Skip to content

Instantly share code, notes, and snippets.

@yume-chan
Created March 19, 2020 09:38
Show Gist options
  • Save yume-chan/a3377341d8c29ed0c9174dca332a1813 to your computer and use it in GitHub Desktop.
Save yume-chan/a3377341d8c29ed0c9174dca332a1813 to your computer and use it in GitHub Desktop.
<canvas id="canvas"></canvas>
<script>
(async () => {
const response = await fetch('./0000.bmp');
const arraybuffer = await response.arrayBuffer();
const dataview = new DataView(arraybuffer);
const offset = dataview.getUint32(10, true);
const width = dataview.getUint32(18, true);
let height = dataview.getInt32(22, true);
const bottomUp = height > 0;
if (!bottomUp) {
height *= -1;
}
const bpp = dataview.getUint16(28, true);
let colors = dataview.getUint32(42, true);
if (colors === 0) {
colors = 1 << bpp;
}
const palette = [];
for (let i = 0; i < colors; i++) {
palette[i] = [
dataview.getUint8(54 + i * 4 + 2), // R
dataview.getUint8(54 + i * 4 + 1), // G
dataview.getUint8(54 + i * 4), // B
];
}
const data = new Uint8ClampedArray(width * height * 4);
for (let sy = 0; sy < height; sy++) {
const dy = bottomUp ? height - sy - 1 : sy;
for (let x = 0; x < width; x++) {
const index = dataview.getUint8(offset + sy * width + x);
const color = palette[index];
data[(dy * width + x) * 4] = color[0];
data[(dy * width + x) * 4 + 1] = color[1];
data[(dy * width + x) * 4 + 2] = color[2];
data[(dy * width + x) * 4 + 3] = 255;
}
}
/** @type {HTMLCanvasElement} */
const canvas = document.getElementById('canvas');
canvas.width = width;
canvas.height = height;
const context = canvas.getContext('2d');
const imageData = new ImageData(data, width, height);
context.putImageData(imageData, 0, 0);
})();
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment