-
-
Save i-like-robots/bb7575fca6b2e76e7d4dfc9949c47211 to your computer and use it in GitHub Desktop.
Visualise ESRI ASCII grid
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const fs = require('fs/promises') | |
const { createCanvas } = require('canvas') | |
function colorScale(p) { | |
if (p === 0) return 'white' | |
if (p < 50) return '#bad2eb' | |
if (p < 250) return '#8ebeda' | |
if (p < 500) return '#5a9ecc' | |
if (p < 1000) return '#357eb9' | |
if (p < 5000) return '#1c5ba6' | |
return '#0b3281' | |
} | |
async function loadData(file) { | |
const content = await fs.readFile(file, 'utf8') | |
const data = [] | |
content.split(/\n+/).forEach((line) => { | |
if (/^[0-9-]/.test(line)) { | |
const items = line.trim().split(/\s+/) | |
data.push(items) | |
} | |
}) | |
return data | |
} | |
async function draw() { | |
// it's only 4.5MB so no need to stream, just bodge! | |
const data = await loadData('./UK_residential_population_2011_1_km.asc') | |
const canvas = createCanvas(652, 1211) | |
const ctx = canvas.getContext('2d') | |
data.forEach((row, y) => { | |
row.forEach((value, x) => { | |
const pop = value === '-9999' ? 0 : parseInt(value, 10) | |
ctx.fillStyle = colorScale(pop) | |
ctx.fillRect(x, y, 1, 1) | |
}) | |
}) | |
await fs.writeFile('./map.png', canvas.toBuffer('image/png')) | |
} | |
draw() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment