Skip to content

Instantly share code, notes, and snippets.

@oskarbraten
Last active September 30, 2022 18:26
Show Gist options
  • Save oskarbraten/6a801807be125df81e190e6c3529b06a to your computer and use it in GitHub Desktop.
Save oskarbraten/6a801807be125df81e190e6c3529b06a to your computer and use it in GitHub Desktop.
Generates mipmaps for a single channel image by processing 4 pixels in the order they appear in the underlying buffer as opposed to visually.
interface SingleChannelImage {
width: number;
height: number;
data: Uint8ClampedArray
}
function mipmaps(source: SingleChannelImage, fn = Math.max): SingleChannelImage[] {
if (source.width === 1 && source.height === 1) {
return [source];
}
const width = Math.max(source.width / 2, 1);
const height = Math.max(source.height / 2, 1);
const length = width * height;
const data = new Uint8ClampedArray(length);
for (let i = 0; i < length; i++) {
const offset = i * 4;
data[i] = fn(...source.data.slice(offset, offset + 4));
}
const result = { width, height, data };
return [source, ...mipmaps(result)];
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment