@thi.ng/pixel-io-pfm
Version:
Portable FloatMap image format support for @thi.ng/pixel
32 lines (31 loc) • 943 B
JavaScript
import { FLOAT_RGB } from "@thi.ng/pixel/format/float-rgb";
import { IntBuffer } from "@thi.ng/pixel/int";
const asPFM = (img, littleEndian = true, linearRGB = true) => {
if (img.format !== FLOAT_RGB) img = img.as(FLOAT_RGB);
const {
width,
height,
data,
stride: [_, strideY]
} = img;
const header = new TextEncoder().encode(
`PF
${width} ${height}
${littleEndian ? -1 : 1}.0
`
);
const buf = new Uint8Array(header.length + width * height * 3 * 4);
const view = new DataView(buf.buffer);
const process = linearRGB ? __srgbLinear : (x) => x;
buf.set(header);
for (let src = (height - 1) * strideY, dest = header.length; src >= 0; src -= strideY) {
for (let x = 0; x < strideY; x++, dest += 4) {
view.setFloat32(dest, process(data[src + x]), littleEndian);
}
}
return buf;
};
const __srgbLinear = (x) => x <= 0.04045 ? x / 12.92 : Math.pow((x + 0.055) / 1.055, 2.4);
export {
asPFM
};