### Encode RGBA Bitmap to HEIC with elheif Source: https://github.com/hpp2334/elheif/blob/main/README.md Example demonstrating how to encode an RGBA bitmap to a HEIC image using elheif. This involves decoding an image first to get the bitmap data, then encoding it. Asserts the encoding error is empty and checks the encoded data length. ```typescript it("encode", async () => { await ensureInitialized(); const buf = loadHeicImage(); const bitmap = jsDecodeImage(buf).data[0]; const encoded = jsEncodeImage(bitmap.data, bitmap.width, bitmap.height); expect(encoded.err).eq(""); expect(encoded.data.length).eq(1288); }); ``` -------------------------------- ### Decode HEIC Image with elheif Source: https://github.com/hpp2334/elheif/blob/main/README.md Example demonstrating how to decode a HEIC image using elheif. Ensure the library is initialized before calling decode. Asserts the error is empty and the decoded image has specific dimensions. ```typescript it("decode", async () => { await ensureInitialized(); const buf = loadHeicImage(); const res = jsDecodeImage(buf); expect(res.err).eq(""); expect(res.data.length).eq(1); expect(res.data[0].width).eq(10); expect(res.data[0].height).eq(10); }); ``` -------------------------------- ### ExternalProject_Add for libheif Source: https://github.com/hpp2334/elheif/blob/main/core/CMakeLists.txt Configures the libheif library, enabling kvazaar support and disabling GDK Pixbuf and examples. It also specifies build options for static libraries and cross-compilation arguments. ```cmake ExternalProject_Add( libheif GIT_REPOSITORY https://github.com/strukturag/libheif.git SOURCE_DIR ${CMAKE_BINARY_DIR}/libheif-src BINARY_DIR ${CMAKE_BINARY_DIR}/libheif-build TEST_COMMAND "" CMAKE_ARGS -DWITH_KVAZAAR=ON -DWITH_GDK_PIXBUF=OFF -DWITH_EXAMPLES=OFF -DENABLE_MULTITHREADING_SUPPORT=OFF -DBUILD_TESTING=OFF -DBUILD_SHARED_LIBS=OFF -DLIBDE265_INCLUDE_DIR=${LIBDE265_INCLUDE_DIR} -DLIBDE265_LIBRARY=${LIBDE265_LIBRARY} -DKVAZAAR_INCLUDE_DIR=${KVAZAAR_INCLUDE_DIR} -DKVAZAAR_LIBRARY=${KVAZAAR_LIBRARY} ${EXTERNAL_PROJECT_EXTRA_CMAKE_ARGS} ) ``` -------------------------------- ### CMakeLists.txt for GoogleTest Integration Source: https://github.com/hpp2334/elheif/blob/main/tests/CMakeLists.txt This CMake script sets up the C++ standard, fetches GoogleTest using FetchContent, defines an executable for tests, and links it with the project library and GoogleTest. It also enables test discovery. ```cmake cmake_minimum_required(VERSION 3.14) include(FetchContent) # GoogleTest requires at least C++14 set(CMAKE_CXX_STANDARD 17) set(CMAKE_CXX_STANDARD_REQUIRED ON) FetchContent_Declare( googletest URL https://github.com/google/googletest/archive/03597a01ee50ed33e9dfd640b249b4be3799d395.zip ) FetchContent_MakeAvailable(googletest) add_executable(elheif-test test.cpp) add_dependencies(elheif-test elheif) target_link_libraries(elheif-test PRIVATE elheif GTest::gtest_main) include(GoogleTest) gtest_discover_tests(elheif-test) ``` -------------------------------- ### Initialization API Source: https://context7.com/hpp2334/elheif/llms.txt The `ensureInitialized` function must be called before using any other API functions. It initializes the WebAssembly module and returns a Promise that resolves when the module is ready. Subsequent calls are safe and return the same promise. ```APIDOC ## Initialization API ### Description Initializes the WebAssembly module. This function must be called before using any other API functions. It returns a Promise that resolves when the WASM module is fully loaded and ready. Calling this function multiple times is safe; subsequent calls will return the same promise. ### Method `ensureInitialized` ### Endpoint N/A (Function call) ### Parameters None ### Request Example ```typescript import { ensureInitialized } from 'elheif'; async function initializeApp() { try { await ensureInitialized(); console.log('elheif WASM module ready'); } catch (error) { console.error('Failed to initialize elheif:', error); } } initializeApp(); ``` ### Response N/A (Returns a Promise that resolves on success or rejects on error) ### Success Response (200) Promise resolves when the WASM module is ready. ### Response Example N/A ``` -------------------------------- ### Initialize the elheif WASM module Source: https://context7.com/hpp2334/elheif/llms.txt Must be called before any other API functions. Subsequent calls return the same promise. ```typescript import { ensureInitialized } from 'elheif'; // Initialize the WASM module before using any other functions async function initializeApp() { try { await ensureInitialized(); console.log('elheif WASM module ready'); // Now safe to call jsDecodeImage and jsEncodeImage } catch (error) { console.error('Failed to initialize elheif:', error); } } initializeApp(); ``` -------------------------------- ### ExternalProject_Add for libde265 Source: https://github.com/hpp2334/elheif/blob/main/core/CMakeLists.txt Configures the libde265 library to be fetched from its Git repository and built. It specifies build options to disable SDL and the decoder, and to build static libraries. ```cmake ExternalProject_Add(libde265 GIT_REPOSITORY https://github.com/strukturag/libde265.git SOURCE_DIR ${CMAKE_BINARY_DIR}/libde265-src BINARY_DIR ${CMAKE_BINARY_DIR}/libde265-build TEST_COMMAND "" CMAKE_ARGS -DENABLE_SDL=OFF -DENABLE_DECODER=OFF -DBUILD_SHARED_LIBS=OFF ${EXTERNAL_PROJECT_EXTRA_CMAKE_ARGS} ) ``` -------------------------------- ### CMake WebAssembly Build Configuration Source: https://github.com/hpp2334/elheif/blob/main/wasm/CMakeLists.txt Defines the executable, compiler standards, and Emscripten-specific linker flags for a WebAssembly target. ```cmake cmake_minimum_required(VERSION 3.14) include(CMakePrintHelpers) set(CMAKE_CXX_STANDARD 17) set(CMAKE_CXX_STANDARD_REQUIRED ON) # set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -pthread") add_executable(elheif-wasm src/impl.cpp) target_compile_definitions(elheif-wasm PUBLIC) add_dependencies(elheif-wasm elheif) target_link_libraries(elheif-wasm PRIVATE elheif # -pthread -lembind -sINITIAL_MEMORY=64MB -sEXPORT_NAME=__ELHEIF_MODULE -sUSE_ES6_IMPORT_META=0 -sSINGLE_FILE=1 -sENVIRONMENT=web,worker -sALLOW_MEMORY_GROWTH=1 -sPTHREAD_POOL_SIZE=1 -sPTHREAD_POOL_SIZE_STRICT=2 -sSTACK_SIZE=1MB ) # https://github.com/clangd/clangd/issues/1621 # make clangd work with emscripten execute_process(COMMAND em++ --cflags OUTPUT_VARIABLE EM_CFLAGS) set_target_properties(elheif-wasm PROPERTIES COMPILE_FLAGS "${EM_CFLAGS}") ``` -------------------------------- ### Emscripten build configuration Source: https://github.com/hpp2334/elheif/blob/main/core/CMakeLists.txt Sets up build flags and toolchain files for Emscripten cross-compilation. This includes defining standalone WASM, setting CMAKE_TOOLCHAIN_FILE, and specifying a cross-compiling emulator. ```cmake set(EXTRA_CXX_FLAGS "-D__EMSCRIPTEN_STANDALONE_WASM__=1") # set(EXTRA_CXX_FLAGS "-D__EMSCRIPTEN_STANDALONE_WASM__=1 -pthread") list(APPEND EXTERNAL_PROJECT_EXTRA_CMAKE_ARGS "-DCMAKE_BUILD_TYPE=${CMAKE_BUILD_TYPE}") list(APPEND EXTERNAL_PROJECT_EXTRA_CMAKE_ARGS "-DCMAKE_INSTALL_PREFIX:PATH=install") list(APPEND EXTERNAL_PROJECT_EXTRA_CMAKE_ARGS -DCMAKE_CXX_FLAGS=${EXTRA_CXX_FLAGS}) list(APPEND EXTERNAL_PROJECT_EXTRA_CMAKE_ARGS -DCMAKE_C_FLAGS=${EXTRA_CXX_FLAGS}) if (EMSCRIPTEN) list(APPEND EXTERNAL_PROJECT_EXTRA_CMAKE_ARGS "-DCMAKE_TOOLCHAIN_FILE=$ENV{EMSCRIPTEN_ROOT}/upstream/emscripten/cmake/Modules/Platform/Emscripten.cmake") list(APPEND EXTERNAL_PROJECT_EXTRA_CMAKE_ARGS "-DCMAKE_CROSSCOMPILING_EMULATOR=$ENV{EMSCRIPTEN_ROOT}/node/16.20.0_64bit/bin/node") endif() # set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -pthread") ``` -------------------------------- ### Initialization and Image Processing Functions Source: https://github.com/hpp2334/elheif/blob/main/README.md Core functions for initializing the WASM module and performing HEIC image encoding and decoding. ```APIDOC ## ensureInitialized ### Description Initializes the WASM module. This must be called and awaited before using any other library functions. ### Method Async Function ### Response - **Promise** - Resolves when the library is ready for use. --- ## jsDecodeImage ### Description Decodes a HEIC image buffer into RGBA bitmaps. ### Parameters - **buf** (Uint8Array) - Required - The HEIC image binary data. ### Response - **DecodeImageResult** (Object) - Contains an error string and an array of image data objects (width, height, and RGBA8888 data). --- ## jsEncodeImage ### Description Encodes an RGBA bitmap into a HEIC image. ### Parameters - **buf** (Uint8Array) - Required - The RGBA8888 bitmap data. - **width** (number) - Required - The width of the image. - **height** (number) - Required - The height of the image. ### Response - **EncodeImageResult** (Object) - Contains an error string and the resulting HEIC binary data as a Uint8Array. ``` -------------------------------- ### Adding elheif static library Source: https://github.com/hpp2334/elheif/blob/main/core/CMakeLists.txt Defines the elheif static library by compiling src/impl.cpp. It sets the C++ standard to 17, adds dependencies on the external projects, and specifies public and private include directories. ```cmake set(CMAKE_CXX_STANDARD 17) add_library(elheif STATIC src/impl.cpp) add_dependencies(elheif kvazaar libde265 libheif) add_dependencies(libheif kvazaar libde265) target_include_directories(elheif PUBLIC include) target_include_directories(elheif PRIVATE ${CMAKE_BINARY_DIR}/libheif-build/install/include) ``` -------------------------------- ### Linking elheif libraries Source: https://github.com/hpp2334/elheif/blob/main/core/CMakeLists.txt Links the elheif library with its dependencies, including -lheif, -lde265, and -lkvazaar. It also specifies library search paths for the external libraries. ```cmake target_link_libraries(elheif PUBLIC # -pthread -lheif -lde265 -lkvazaar -L${KVAZAAR_LIBRARY_DIR} -L${LIBDE265_LIBRARY_DIR} -L${LIBHEIF_LIBRARY_DIR} ) ``` -------------------------------- ### elheif API Interfaces and Functions Source: https://github.com/hpp2334/elheif/blob/main/README.md Defines the interfaces for decoding and encoding results, and the core functions for initializing the library, decoding HEIC images, and encoding RGBA bitmaps to HEIC. ```typescript interface DecodeImageResult { err: string; data: Array<{ width: number; height: number; /** RGBA8888 bitmap */ data: Uint8Array; }>; } ``` ```typescript interface EncodeImageResult { err: string; data: Uint8Array; } ``` ```typescript /** Should be called and wait till promise fulfilled when using other APIs */ export function ensureInitialized(): Promise; ``` ```typescript /** Convert heic image to RGBA bitmaps */ export function jsDecodeImage(buf: Uint8Array): DecodeImageResult; ``` ```typescript /** Convert RGBA bitmap to heic image */ export function jsEncodeImage( buf: Uint8Array, width: number, height: number ): EncodeImageResult; ``` -------------------------------- ### ExternalProject_Add for kvazaar Source: https://github.com/hpp2334/elheif/blob/main/core/CMakeLists.txt Configures the kvazaar library to be fetched from its Git repository and built as a dependency. It includes specific CMake arguments and a patch command to modify CMakeLists.txt. ```cmake ExternalProject_Add( kvazaar GIT_REPOSITORY https://github.com/ultravideo/kvazaar.git SOURCE_DIR ${CMAKE_BINARY_DIR}/kvazaar-src BINARY_DIR ${CMAKE_BINARY_DIR}/kvazaar-build TEST_COMMAND "" PATCH_COMMAND sed -i "/-muse-unaligned-vector-move/d" ${CMAKE_BINARY_DIR}/kvazaar-src/CMakeLists.txt CMAKE_ARGS -DBUILD_TESTS=OFF -DBUILD_SHARED_LIBS=OFF ${EXTERNAL_PROJECT_EXTRA_CMAKE_ARGS} ) ``` -------------------------------- ### Encode RGBA data to HEIC Source: https://context7.com/hpp2334/elheif/llms.txt Encodes raw RGBA8888 pixel data into a HEIC image. Requires image dimensions for processing. ```typescript import { ensureInitialized, jsEncodeImage } from 'elheif'; interface EncodeImageResult { err: string; data: Uint8Array; } async function encodeToHeic( rgbaData: Uint8Array, width: number, height: number ): Promise { await ensureInitialized(); const result: EncodeImageResult = jsEncodeImage(rgbaData, width, height); if (result.err !== "") { console.error('Encode error:', result.err); return null; } console.log(`Encoded HEIC size: ${result.data.length} bytes`); return result.data; } // Example: Convert canvas to HEIC async function canvasToHeic(canvas: HTMLCanvasElement): Promise { const ctx = canvas.getContext('2d'); const imageData = ctx.getImageData(0, 0, canvas.width, canvas.height); const rgbaBuffer = new Uint8Array(imageData.data.buffer); const heicData = await encodeToHeic(rgbaBuffer, canvas.width, canvas.height); if (heicData) { return new Blob([heicData], { type: 'image/heic' }); } return null; } // Example: Download encoded HEIC file async function downloadAsHeic(canvas: HTMLCanvasElement, filename: string) { const blob = await canvasToHeic(canvas); if (blob) { const url = URL.createObjectURL(blob); const link = document.createElement('a'); link.href = url; link.download = filename; link.click(); URL.revokeObjectURL(url); } } ``` -------------------------------- ### jsDecodeImage API Source: https://context7.com/hpp2334/elheif/llms.txt Decodes a HEIC image buffer into raw RGBA8888 bitmap data. It accepts a Uint8Array of HEIC file data and returns an object containing an error string and an array of decoded image frames, each with width, height, and RGBA pixel data. ```APIDOC ## Decode Image API ### Description Decodes a HEIC image buffer into raw RGBA8888 bitmap data. The function accepts a `Uint8Array` containing the HEIC file data and returns a result object with an error string (empty on success) and an array of decoded image frames. Each frame contains width, height, and the raw RGBA pixel data. ### Method `jsDecodeImage` ### Endpoint N/A (Function call) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **heicBuffer** (Uint8Array) - Required - A buffer containing the HEIC file data. ### Request Example ```typescript import { ensureInitialized, jsDecodeImage } from 'elheif'; interface DecodeImageResult { err: string; data: Array<{ width: number; height: number; data: Uint8Array }>; } async function decodeHeicImage(heicBuffer: Uint8Array): Promise { await ensureInitialized(); const result: DecodeImageResult = jsDecodeImage(heicBuffer); if (result.err !== "") { console.error('Decode error:', result.err); return; } for (let i = 0; i < result.data.length; i++) { const frame = result.data[i]; console.log(`Frame ${i}: ${frame.width}x${frame.height}`); // Process frame data... } } ``` ### Response #### Success Response (200) - **err** (string) - An empty string if decoding was successful. - **data** (Array) - An array of decoded image frames. Each object has: - **width** (number) - The width of the image frame. - **height** (number) - The height of the image frame. - **data** (Uint8Array) - The raw RGBA8888 pixel data. #### Response Example ```json { "err": "", "data": [ { "width": 1920, "height": 1080, "data": "" } ] } ``` ``` -------------------------------- ### Decode HEIC images to RGBA Source: https://context7.com/hpp2334/elheif/llms.txt Decodes a HEIC buffer into raw RGBA8888 bitmap data. HEIC files may contain multiple frames. ```typescript import { ensureInitialized, jsDecodeImage } from 'elheif'; interface DecodeImageResult { err: string; data: Array<{ width: number; height: number; /** RGBA8888 bitmap - 4 bytes per pixel */ data: Uint8Array; }>; } async function decodeHeicImage(heicBuffer: Uint8Array): Promise { await ensureInitialized(); const result: DecodeImageResult = jsDecodeImage(heicBuffer); if (result.err !== "") { console.error('Decode error:', result.err); return; } // Process each frame (HEIC can contain multiple images) for (let i = 0; i < result.data.length; i++) { const frame = result.data[i]; console.log(`Frame ${i}: ${frame.width}x${frame.height}`); console.log(`Pixel data size: ${frame.data.length} bytes`); // Draw to canvas const canvas = document.createElement('canvas'); canvas.width = frame.width; canvas.height = frame.height; const ctx = canvas.getContext('2d'); const imageData = new ImageData( new Uint8ClampedArray(frame.data), frame.width, frame.height ); ctx.putImageData(imageData, 0, 0); document.body.appendChild(canvas); } } // Usage with file input const fileInput = document.querySelector('input[type="file"]'); fileInput.addEventListener('change', async (event) => { const file = event.target.files[0]; const arrayBuffer = await file.arrayBuffer(); const heicBuffer = new Uint8Array(arrayBuffer); await decodeHeicImage(heicBuffer); }); ``` -------------------------------- ### Decode and Re-encode HEIC Image in TypeScript Source: https://context7.com/hpp2334/elheif/llms.txt Performs a full round-trip of decoding a HEIC image, performing optional pixel manipulation, and re-encoding the result. ```typescript import { ensureInitialized, jsDecodeImage, jsEncodeImage } from 'elheif'; async function processHeicImage(inputBuffer: Uint8Array): Promise { // Ensure WASM module is initialized await ensureInitialized(); // Decode the HEIC image const decodeResult = jsDecodeImage(inputBuffer); if (decodeResult.err !== "") { console.error('Decode failed:', decodeResult.err); return null; } if (decodeResult.data.length === 0) { console.error('No frames found in HEIC image'); return null; } // Get the first frame const frame = decodeResult.data[0]; console.log(`Decoded: ${frame.width}x${frame.height}, ${frame.data.length} bytes`); // Optional: Modify the pixel data here // Example: Invert colors for (let i = 0; i < frame.data.length; i += 4) { frame.data[i] = 255 - frame.data[i]; // R frame.data[i + 1] = 255 - frame.data[i + 1]; // G frame.data[i + 2] = 255 - frame.data[i + 2]; // B // Alpha (i + 3) unchanged } // Re-encode to HEIC const encodeResult = jsEncodeImage(frame.data, frame.width, frame.height); if (encodeResult.err !== "") { console.error('Encode failed:', encodeResult.err); return null; } console.log(`Encoded: ${encodeResult.data.length} bytes`); return encodeResult.data; } // Utility: Convert base64 to Uint8Array function base64ToUint8Array(base64: string): Uint8Array { const binaryString = atob(base64); const bytes = new Uint8Array(binaryString.length); for (let i = 0; i < binaryString.length; i++) { bytes[i] = binaryString.charCodeAt(i); } return bytes; } // Utility: Convert Uint8Array to base64 function uint8ArrayToBase64(bytes: Uint8Array): string { let binary = ''; for (let i = 0; i < bytes.length; i++) { binary += String.fromCharCode(bytes[i]); } return btoa(binary); } ``` -------------------------------- ### jsEncodeImage API Source: https://context7.com/hpp2334/elheif/llms.txt Encodes raw RGBA8888 bitmap data into a HEIC image. It takes RGBA pixel data, width, and height, and returns a result object with the encoded HEIC file data or an error message. ```APIDOC ## Encode Image API ### Description Encodes raw RGBA8888 bitmap data into a HEIC image. The function accepts a `Uint8Array` of RGBA pixel data along with the image dimensions, and returns a result object containing the encoded HEIC file data or an error message. ### Method `jsEncodeImage` ### Endpoint N/A (Function call) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **rgbaData** (Uint8Array) - Required - The raw RGBA8888 pixel data. - **width** (number) - Required - The width of the image. - **height** (number) - Required - The height of the image. ### Request Example ```typescript import { ensureInitialized, jsEncodeImage } from 'elheif'; interface EncodeImageResult { err: string; data: Uint8Array; } async function encodeToHeic( rgbaData: Uint8Array, width: number, height: number ): Promise { await ensureInitialized(); const result: EncodeImageResult = jsEncodeImage(rgbaData, width, height); if (result.err !== "") { console.error('Encode error:', result.err); return null; } console.log(`Encoded HEIC size: ${result.data.length} bytes`); return result.data; } ``` ### Response #### Success Response (200) - **err** (string) - An empty string if encoding was successful. - **data** (Uint8Array) - The encoded HEIC file data. #### Response Example ```json { "err": "", "data": "" } ``` ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.