Skip to content

API Reference

Core Functions

encodeToKTX2

The main function for converting images to KTX2 format.

typescript
// Browser
async function encodeToKTX2(
  imageBuffer: Uint8Array | CubeBufferData,
  options?: Partial<IEncodeOptions>
): Promise<Uint8Array>;

// Node.js
async function encodeToKTX2(imageBuffer: Uint8Array, options?: Partial<IEncodeOptions>): Promise<Uint8Array>;

Parameters

  • imageBuffer: Encoded image data as a Uint8Array. In browsers, a tuple of exactly six image buffers creates a cubemap in the order [posx, negx, posy, negy, posz, negz].
  • options: Optional configuration object (see IEncodeOptions below)

Example

typescript
import { encodeToKTX2 } from "ktx2-encoder";

const ktx2Data = await encodeToKTX2(imageBuffer, {
  isUASTC: true,
  generateMipmap: true,
  isNormalMap: false
});

Configuration Options

IEncodeOptions Interface

Complete configuration options for the encoder:

OptionTypeDefaultDescription
isUASTCbooleantrueUse UASTC texture format instead of ETC1S
enableDebugbooleanfalseEnable debug output
isYFlipbooleanfalseIf true, the source images will be Y flipped before compression
qualityLevelnumber150Sets the ETC1S encoder's quality level (1-255). Controls file size vs. quality tradeoff
compressionLevelnumber2Controls encoder performance vs. file size tradeoff for ETC1S files (0-6)
needSupercompressionbooleantrueUse UASTC Zstandard supercompression
uastcLDRQualityLevelnumber1Controls UASTC LDR quality (0-3); higher values are slower and higher quality
enableRDObooleanfalseEnable UASTC LDR rate-distortion optimization
rdoQualityLevelnumber1.0Controls UASTC RDO quality (0.001-10); lower values favor quality
isNormalMapbooleanfalseOptimize compression parameters for normal maps
isPerceptualbooleanencoder defaultTreat input as perceptual/sRGB data; normally true for color textures and false for normal maps
isSetKTX2SRGBTransferFuncbooleantrueUse the sRGB transfer function in the KTX2 DFD; normally matches isPerceptual
generateMipmapbooleantrueGenerate mipmaps from source images
isKTX2FilebooleantrueCreate a KTX2 file instead of a Basis file
isHDRbooleanfalseEnable UASTC HDR encoding
imageType"hdr" | "exr"required for HDRSupported HDR source container type
hdrQualityLevelnumberencoder defaultControls UASTC HDR quality (0-4)
kvDataRecord<string, string | Uint8Array>undefinedCustom key-value metadata for the KTX2 file
outputBufferSizenumberestimatedInitial output buffer capacity in bytes; encoding retries once at twice this size on failure
imageDecoderFunctionbrowser built-inFunction that decodes an image buffer to RGBA; required in Node.js for non-HDR images
jsUrlstringundefinedDeprecated and ignored in browsers; the bundled JavaScript module is always used
wasmUrlstringbundled assetBrowser-only URL overriding the bundled single-threaded WebAssembly module; also used when a useThreads request falls back to single-threaded
threadsWasmUrlstringbundled assetBrowser-only URL overriding the bundled multithreaded WebAssembly module; used only when useThreads is active on a cross-origin isolated page
useThreadsbooleanfalseBrowser-only. Opt into multithreaded encoding; requires a cross-origin isolated page, falls back to single-threaded otherwise. Ignored in Node.js
numThreadsnumbermin(hardwareConcurrency - 1, 8)Extra worker threads when useThreads is active (total = 1 + numThreads); clamped to [0, 8], 0 disables

Image Decoder Function Type

For Node.js usage, the imageDecoder function should match this signature:

typescript
type ImageDecoder = (buffer: Uint8Array) => Promise<{
  width: number;
  height: number;
  data: Uint8Array;
}>;

Examples

Basic Usage

typescript
const ktx2Data = await encodeToKTX2(imageBuffer, {
  isUASTC: true,
  generateMipmap: true,
  isNormalMap: false
});

Normal Map Compression

typescript
const normalMapData = await encodeToKTX2(normalMapBuffer, {
  isUASTC: true, // Recommended for normal maps
  isNormalMap: true,
  isSetKTX2SRGBTransferFunc: false // Important for normal maps
});

ETC1S with Quality Settings

typescript
const etc1sData = await encodeToKTX2(imageBuffer, {
  isUASTC: false,
  qualityLevel: 128,
  compressionLevel: 2
});

Cubemap Encoding

typescript
import { encodeToKTX2 } from "ktx2-encoder";

// Load your 6 cubemap face images
Promise.all([
  loadImage("posx.jpg"),
  loadImage("negx.jpg"),
  loadImage("posy.jpg"),
  loadImage("negy.jpg"),
  loadImage("posz.jpg"),
  loadImage("negz.jpg")
]).then((buffers) => {
  // Encode to KTX2 cubemap
  return encodeToKTX2(buffers, {
    isUASTC: true,
    generateMipmap: true,
    qualityLevel: 128
  });
});

Cubemap encoding through the package entry point is currently available in browser builds.

Face Order

The cubemap faces must be provided in this specific order:

  • posx: Positive X face (+X)
  • negx: Negative X face (-X)
  • posy: Positive Y face (+Y)
  • negy: Negative Y face (-Y)
  • posz: Positive Z face (+Z)
  • negz: Negative Z face (-Z)

With Custom Metadata

typescript
const ktx2Data = await encodeToKTX2(imageBuffer, {
  kvData: {
    myKey: "myValue",
    customData: new Uint8Array([1, 2, 3])
  }
});