### Install Colopresso Python Bindings Source: https://github.com/colopl/colopresso/blob/main/python/README.md Instructions for installing the Colopresso Python library using pip. This includes standard installation, installation from source, and development setup. ```bash pip install "colopresso" ``` ```bash cd python pip install . ``` ```bash cd python pip install -e ".[dev]" ``` -------------------------------- ### Fast CI Valgrind Run Example (Linux) Source: https://github.com/colopl/colopresso/blob/main/README.md An example of a faster Valgrind run configuration, suitable for CI environments, by disabling origin tracking and limiting Rayon threads. ```bash rm -rf "build" && cmake -B "build" -DCMAKE_BUILD_TYPE=Debug \ -DCOLOPRESSO_USE_VALGRIND=ON -DCOLOPRESSO_USE_TESTS=ON \ -DCOLOPRESSO_VALGRIND_TRACK_ORIGINS=OFF -DCOLOPRESSO_VALGRIND_RAYON_NUM_THREADS=1 ``` -------------------------------- ### Quick Start: Encode PNG Images with Colopresso Source: https://github.com/colopl/colopresso/blob/main/python/README.md A basic example demonstrating how to read a PNG file and encode it into WebP, AVIF, and optimized PNG (PNGX) formats using the Colopresso Python library. ```python import colopresso # Read PNG file with open("input.png", "rb") as f: png_data = f.read() # Convert to WebP webp_data = colopresso.encode_webp(png_data) with open("output.webp", "wb") as f: f.write(webp_data) # Convert to AVIF avif_data = colopresso.encode_avif(png_data) with open("output.avif", "wb") as f: f.write(avif_data) # Optimize PNG optimized_png = colopresso.encode_pngx(png_data) with open("output.png", "wb") as f: f.write(optimized_png) ``` -------------------------------- ### WebP Conversion Example Source: https://github.com/colopl/colopresso/blob/main/python/README.md Demonstrates how to convert PNG images to WebP format with different quality and compression settings. ```APIDOC ## Examples ### WebP Conversion with Quality Settings ```python import colopresso with open("photo.png", "rb") as f: png_data = f.read() # High quality WebP config = colopresso.Config( webp_quality=95.0, webp_method=6, webp_use_sharp_yuv=True ) high_quality = colopresso.encode_webp(png_data, config) # High compression WebP config = colopresso.Config( webp_quality=60.0, webp_method=6 ) compressed = colopresso.encode_webp(png_data, config) # Lossless WebP config = colopresso.Config(webp_lossless=True) lossless = colopresso.encode_webp(png_data, config) ``` ``` -------------------------------- ### AVIF Conversion with Multithreading Example Source: https://github.com/colopl/colopresso/blob/main/python/README.md Shows an example of converting PNG images to AVIF format utilizing multithreading for faster encoding. ```APIDOC ### AVIF with Multithreading ```python import colopresso with open("large_image.png", "rb") as f: png_data = f.read() # Multithreaded high-speed encoding config = colopresso.Config( avif_quality=70.0, avif_speed=6, avif_threads=4 ) avif_data = colopresso.encode_avif(png_data, config) ``` ``` -------------------------------- ### Project Setup and C Standard Configuration (CMake) Source: https://github.com/colopl/colopresso/blob/main/CMakeLists.txt Initializes the CMake build system, defines the project name, version, and language, and sets the C standard to C99 with required compliance. It also configures position-independent code generation. ```cmake cmake_minimum_required(VERSION 3.22) project(colopresso VERSION 0.0.0 LANGUAGES C DESCRIPTION "PNG compressor and converter" ) set(CMAKE_C_STANDARD 99) set(CMAKE_C_STANDARD_REQUIRED ON) set(CMAKE_POSITION_INDEPENDENT_CODE ON) ``` -------------------------------- ### Execute CLI Conversion Commands Source: https://context7.com/colopl/colopresso/llms.txt Provides examples of using the colopresso command-line interface to convert images between formats and apply specific encoding options. ```bash # Basic conversions colopresso input.png output.webp colopresso --format=avif input.png output colopresso --format=pngx input.png output.png # WebP specific options colopresso --format=webp --quality=95 --method=6 input.png output.webp colopresso --format=webp --lossless input.png output.webp colopresso --format=webp --size=50000 input.png output.webp # AVIF specific options colopresso --format=avif --quality=80 --speed=4 input.png output.avif colopresso --format=avif --quality=60 --speed=8 --threads=8 input.png output.avif ``` -------------------------------- ### Run Specific Valgrind Test Example (Linux) Source: https://github.com/colopl/colopresso/blob/main/README.md Example command to run only a specific Valgrind test, identified by its name, using ctest. ```bash ctest --test-dir "build" --output-on-failure -R '^test_encode_pngx_memory_valgrind$' ``` -------------------------------- ### Optimize PNG with Colopresso (PNGX) Source: https://github.com/colopl/colopresso/blob/main/python/README.md Illustrates optimizing PNG data using the `encode_pngx` function, with an example of enabling lossy compression and setting a 256-color palette. ```python import colopresso with open("input.png", "rb") as f: png_data = f.read() # 256-color palette optimization config = colopresso.Config( pngx_lossy_enable=True, pngx_lossy_type=colopresso.PngxLossyType.PALETTE256, pngx_lossy_max_colors=256 ) optimized = colopresso.encode_pngx(png_data, config) ``` -------------------------------- ### Build Colopresso for Electron (macOS and Windows) Source: https://github.com/colopl/colopresso/blob/main/README.md Builds the Electron application for macOS and Windows, including EMSDK setup and platform-specific build flags. ```bash # macOS Setup and Build cd third_party/emsdk ./emsdk install ./emsdk activate source ./emsdk_env.sh cd ../.. rm -rf "build" && emcmake cmake -B "build" -DCOLOPRESSO_ELECTRON_APP=ON -DCOLOPRESSO_ELECTRON_TARGETS="--mac" cmake --build "build" --config Release --parallel ``` ```powershell # Windows Setup and Build cd third_party/emsdk .\emsdk.ps1 install .\emsdk.ps1 activate . .\emsdk_env.ps1 cd ..\.. rm -rf "build" emcmake cmake -B "build" -DCOLOPRESSO_ELECTRON_APP=ON -DCOLOPRESSO_ELECTRON_TARGETS="--win" cmake --build "build" --config Release --parallel ``` -------------------------------- ### Project Installation Configuration (CMake) Source: https://github.com/colopl/colopresso/blob/main/CMakeLists.txt This snippet includes the CMake script responsible for handling the installation of the Colopresso project. It relies on an external 'cmake/install.cmake' file to manage installation rules. ```cmake include(cmake/install.cmake) ``` -------------------------------- ### Convert PNG to WebP with Python Source: https://context7.com/colopl/colopresso/llms.txt Demonstrates how to convert PNG image data to WebP format using the colopresso library. It includes examples for basic conversion, high-quality settings, lossless compression, and near-lossless optimization with target file sizes. ```python import colopresso # Read PNG file with open("input.png", "rb") as f: png_data = f.read() # Basic WebP conversion with default settings (quality=80, lossy) webp_data = colopresso.encode_webp(png_data) with open("output.webp", "wb") as f: f.write(webp_data) # High quality WebP with sharp YUV conversion config = colopresso.Config( webp_quality=95.0, webp_method=6, # Best compression (0-6) webp_use_sharp_yuv=True # Better color accuracy ) webp_hq = colopresso.encode_webp(png_data, config) # Lossless WebP compression config = colopresso.Config(webp_lossless=True) webp_lossless = colopresso.encode_webp(png_data, config) # Near-lossless with target file size config = colopresso.Config( webp_quality=80.0, webp_near_lossless=60, # 0-100, higher = closer to lossless webp_target_size=50000 # Target ~50KB ) webp_optimized = colopresso.encode_webp(png_data, config) print(f"Original: {len(png_data)} bytes") print(f"WebP: {len(webp_data)} bytes") print(f"Reduction: {(1 - len(webp_data)/len(png_data))*100:.1f}%") ``` -------------------------------- ### Configure Rust Toolchain for Electron Source: https://github.com/colopl/colopresso/blob/main/README.md Installs the required Rust nightly toolchain and WebAssembly targets necessary for Electron builds. ```bash rustup toolchain install nightly rustup component add "rust-src" --toolchain nightly rustup target add "wasm32-unknown-emscripten" rustup target add "wasm32-unknown-unknown" ``` -------------------------------- ### Third-Party Library Configuration (zlib, libpng, libwebp, libavif) Source: https://github.com/colopl/colopresso/blob/main/python/CMakeLists.txt Configures build settings for essential third-party libraries including zlib, libpng, libwebp, and libavif. This includes disabling tests and examples, enforcing static library builds where appropriate, and setting specific compiler options for optimal performance. It ensures these libraries are correctly integrated into the Colopresso build process. ```cmake # zlib configuration set(ZLIB_BUILD_TESTING OFF CACHE BOOL "" FORCE) set(ZLIB_BUILD_EXAMPLES OFF CACHE BOOL "" FORCE) # libpng configuration set(PNG_SHARED OFF CACHE BOOL "" FORCE) set(PNG_STATIC ON CACHE BOOL "" FORCE) set(PNG_TESTS OFF CACHE BOOL "" FORCE) set(PNG_EXECUTABLES OFF CACHE BOOL "" FORCE) set(PNG_TOOLS OFF CACHE BOOL "" FORCE) set(PNG_DEBUG OFF CACHE BOOL "" FORCE) set(PNG_HARDWARE_OPTIMIZATIONS ON CACHE BOOL "" FORCE) # libwebp configuration set(WEBP_BUILD_ANIM_UTILS OFF CACHE BOOL "" FORCE) set(WEBP_BUILD_CWEBP OFF CACHE BOOL "" FORCE) set(WEBP_BUILD_DWEBP OFF CACHE BOOL "" FORCE) set(WEBP_BUILD_GIF2WEBP OFF CACHE BOOL "" FORCE) set(WEBP_BUILD_IMG2WEBP OFF CACHE BOOL "" FORCE) set(WEBP_BUILD_VWEBP OFF CACHE BOOL "" FORCE) set(WEBP_BUILD_WEBPINFO OFF CACHE BOOL "" FORCE) set(WEBP_BUILD_LIBWEBPMUX ON CACHE BOOL "" FORCE) set(WEBP_BUILD_WEBPMUX OFF CACHE BOOL "" FORCE) set(WEBP_BUILD_EXTRAS OFF CACHE BOOL "" FORCE) set(WEBP_BUILD_FUZZTEST OFF CACHE BOOL "" FORCE) # libavif configuration set(AVIF_ENABLE_WERROR OFF CACHE BOOL "" FORCE) set(AVIF_BUILD_APPS OFF CACHE BOOL "" FORCE) set(AVIF_BUILD_EXAMPLES OFF CACHE BOOL "" FORCE) set(AVIF_BUILD_TESTS OFF CACHE BOOL "" FORCE) set(AVIF_LIBYUV OFF CACHE STRING "" FORCE) set(AVIF_CODEC_AOM "LOCAL" CACHE STRING "" FORCE) set(AVIF_CODEC_AOM_ENCODE ON CACHE BOOL "" FORCE) set(AVIF_CODEC_AOM_DECODE OFF CACHE STRING "" FORCE) set(AVIF_CODEC_DAV1D OFF CACHE STRING "" FORCE) set(AVIF_CODEC_LIBGAV1 OFF CACHE STRING "" FORCE) set(AVIF_CODEC_RAV1E OFF CACHE STRING "" FORCE) set(AVIF_CODEC_SVT OFF CACHE STRING "" FORCE) set(AVIF_CODEC_AVM OFF CACHE STRING "" FORCE) # Force static library for libavif (avoid runtime dependency) set(BUILD_SHARED_LIBS OFF CACHE BOOL "" FORCE) set(COLOPRESSO_BACKUP_BUILD_TESTING ${BUILD_TESTING}) set(BUILD_TESTING OFF) # zlib set(CMAKE_SUPPRESS_DEVELOPER_WARNINGS ON CACHE BOOL "" FORCE) add_subdirectory("${COLOPRESSO_ROOT}/third_party/zlib" "${CMAKE_CURRENT_BINARY_DIR}/third_party/zlib" EXCLUDE_FROM_ALL) set(CMAKE_SUPPRESS_DEVELOPER_WARNINGS OFF CACHE BOOL "" FORCE) if(TARGET zlib) get_target_property(ZLIB_TYPE zlib TYPE) if(ZLIB_TYPE STREQUAL "SHARED_LIBRARY" OR ZLIB_TYPE STREQUAL "STATIC_LIBRARY") set_target_properties(zlib PROPERTIES EXCLUDE_FROM_ALL TRUE) endif() endif() # Set ZLIB_ROOT for libpng set(ZLIB_ROOT "${CMAKE_CURRENT_BINARY_DIR}/third_party/zlib" CACHE PATH "" FORCE) set(ZLIB_INCLUDE_DIR "${COLOPRESSO_ROOT}/third_party/zlib;${CMAKE_CURRENT_BINARY_DIR}/third_party/zlib" CACHE PATH "" FORCE) set(ZLIB_LIBRARY "${CMAKE_CURRENT_BINARY_DIR}/third_party/zlib/libz.a" CACHE FILEPATH "" FORCE) # libpng add_subdirectory("${COLOPRESSO_ROOT}/third_party/libpng" "${CMAKE_CURRENT_BINARY_DIR}/third_party/libpng" EXCLUDE_FROM_ALL) # libwebp add_subdirectory("${COLOPRESSO_ROOT}/third_party/libwebp" "${CMAKE_CURRENT_BINARY_DIR}/third_party/libwebp" EXCLUDE_FROM_ALL) # libavif add_subdirectory("${COLOPRESSO_ROOT}/third_party/libavif" "${CMAKE_CURRENT_BINARY_DIR}/third_party/libavif" EXCLUDE_FROM_ALL) set(BUILD_TESTING ${COLOPRESSO_BACKUP_BUILD_TESTING}) ``` -------------------------------- ### Colopresso CMake Project Setup Source: https://github.com/colopl/colopresso/blob/main/python/CMakeLists.txt Initializes the CMake project, sets C++ standards, and configures build options for Colopresso. It defines project name, language, C standard, and position-independent code settings. It also forces specific build configurations for Python bindings, CLI, tests, and utilities. ```cmake cmake_minimum_required(VERSION 3.22) project(colopresso_python LANGUAGES C) set(CMAKE_C_STANDARD 99) set(CMAKE_C_STANDARD_REQUIRED ON) set(CMAKE_POSITION_INDEPENDENT_CODE ON) include(GNUInstallDirs) include(FetchContent) set(COLOPRESSO_PYTHON_BINDINGS ON CACHE BOOL "Build Python bindings" FORCE) set(COLOPRESSO_USE_CLI OFF CACHE BOOL "Build CLI" FORCE) set(COLOPRESSO_USE_TESTS OFF CACHE BOOL "Build tests" FORCE) set(COLOPRESSO_USE_UTILS OFF CACHE BOOL "Build utils" FORCE) get_filename_component(COLOPRESSO_ROOT "${CMAKE_CURRENT_SOURCE_DIR}/.." ABSOLUTE) set(CMAKE_MODULE_PATH "${COLOPRESSO_ROOT}/cmake" ${CMAKE_MODULE_PATH}) include(options) include(compiler) colopresso_configure_threads() colopresso_apply_global_threads_compile_options() colopresso_configure_debug() colopresso_configure_simd() ``` -------------------------------- ### Encode PNG to WebP with Colopresso Source: https://github.com/colopl/colopresso/blob/main/python/README.md Demonstrates encoding PNG data to WebP format using the `encode_webp` function. Includes examples for default settings and custom quality configurations. ```python import colopresso with open("input.png", "rb") as f: png_data = f.read() # Default settings webp_data = colopresso.encode_webp(png_data) # Custom quality config = colopresso.Config(webp_quality=90.0) webp_data = colopresso.encode_webp(png_data, config) ``` -------------------------------- ### Encode PNG to AVIF with Colopresso Source: https://github.com/colopl/colopresso/blob/main/python/README.md Shows how to encode PNG data to AVIF format using the `encode_avif` function. Provides an example with custom quality and speed settings. ```python import colopresso with open("input.png", "rb") as f: png_data = f.read() config = colopresso.Config(avif_quality=70.0, avif_speed=4) avif_data = colopresso.encode_avif(png_data, config) ``` -------------------------------- ### Encode Images to WebP Source: https://github.com/colopl/colopresso/blob/main/python/README.md Examples of encoding PNG data into WebP format using different quality and compression strategies. The configuration object allows fine-tuning of quality, method, and lossless settings. ```python import colopresso with open("photo.png", "rb") as f: png_data = f.read() # High quality WebP config = colopresso.Config( webp_quality=95.0, webp_method=6, webp_use_sharp_yuv=True ) high_quality = colopresso.encode_webp(png_data, config) # High compression WebP config = colopresso.Config( webp_quality=60.0, webp_method=6 ) compressed = colopresso.encode_webp(png_data, config) # Lossless WebP config = colopresso.Config(webp_lossless=True) lossless = colopresso.encode_webp(png_data, config) ``` -------------------------------- ### Convert images to AVIF via CLI Source: https://context7.com/colopl/colopresso/llms.txt Demonstrates how to convert PNG images to AVIF format using the command line. Includes options for lossless compression and custom alpha channel quality settings. ```bash colopresso --format=avif --lossless input.png output.avif colopresso --format=avif --quality=70 --alpha-q=100 input.png output.avif ``` -------------------------------- ### ColopressoError Exception Class Source: https://github.com/colopl/colopresso/blob/main/python/README.md Details about the ColopressoError exception, including error codes and usage examples. ```APIDOC ## Exception Classes ### ColopressoError ```python class ColopressoError(Exception): code: int # Error code message: str # Error message ``` **Error Codes:** | Code | Name | Description | |---|---|---| | 0 | OK | Success | | 1 | File not found | File not found | | 2 | Invalid PNG | Invalid PNG data | | 3 | Invalid format | Invalid format | | 4 | Out of memory | Memory allocation failed | | 5 | Encode failed | Encoding failed | | 6 | Decode failed | Decoding failed | | 7 | IO error | Input/output error | | 8 | Invalid parameter | Invalid parameter | | 9 | Output not smaller | Output is not smaller than input | **Example:** ```python import colopresso try: result = colopresso.encode_avif(png_data) except colopresso.ColopressoError as e: if e.code == 9: print("AVIF compression was not effective. Using original PNG.") else: print(f"Error: {e.message}") ``` ``` -------------------------------- ### Initialize and convert images using Node.js API Source: https://context7.com/colopl/colopresso/llms.txt Shows how to initialize the Colopresso WebAssembly module and perform conversions to WebP, AVIF, and PNGX formats. Includes error handling for cases where output size exceeds input size. ```typescript import { initializeModule, convertPngToWebp, convertPngToAvif, convertPngToPngx, getVersionInfo, OutputLargerThanInputError } from 'colopresso/converter'; import colopressoFactory from 'colopresso/wasm'; import { readFileSync, writeFileSync } from 'fs'; async function main() { const Module = await initializeModule(colopressoFactory); const pngData = new Uint8Array(readFileSync('input.png')); const webpData = convertPngToWebp(Module, pngData, { quality: 85, method: 6, lossless: false }); writeFileSync('output.webp', webpData); const avifData = convertPngToAvif(Module, pngData, { quality: 70, speed: 4 }); writeFileSync('output.avif', avifData); const pngxData = convertPngToPngx(Module, pngData, { pngx_lossy_enable: true, pngx_lossy_type: 0, pngx_lossy_max_colors: 256, pngx_lossy_quality_min: 85, pngx_lossy_quality_max: 100 }); writeFileSync('output.png', pngxData); const versions = getVersionInfo(Module); console.log('Versions:', versions); } async function safeConvert(Module: any, pngData: Uint8Array) { try { return convertPngToAvif(Module, pngData, { quality: 60 }); } catch (e) { if (e instanceof OutputLargerThanInputError) { console.log('AVIF not effective for this image'); return pngData; } throw e; } } main(); ``` -------------------------------- ### Build Utility Programs (CMake) Source: https://github.com/colopl/colopresso/blob/main/CMakeLists.txt This snippet demonstrates how to build utility executables using CMake when COLOPRESSO_USE_UTILS is enabled. It finds all .c files in the 'library/utils' directory, creates an executable for each, links them against the 'colopresso' library, and sets their output directory and name. ```cmake if(COLOPRESSO_USE_UTILS) if(COLOPRESSO_DISABLE_FILE_OPS) message(WARNING "Skipping utils build (COLOPRESSO_DISABLE_FILE_OPS=ON)") else() file(GLOB UTIL_SOURCES "library/utils/*.c") foreach(UTIL_SOURCE ${UTIL_SOURCES}) get_filename_component(UTIL_NAME ${UTIL_SOURCE} NAME_WE) set(UTIL_TARGET "util_${UTIL_NAME}") add_executable(${UTIL_TARGET} ${UTIL_SOURCE}) target_link_libraries(${UTIL_TARGET} PRIVATE colopresso) set(_util_properties RUNTIME_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/utils OUTPUT_NAME ${UTIL_NAME} ) if(EMSCRIPTEN) list(APPEND _util_properties SUFFIX ".js") endif() set_target_properties(${UTIL_TARGET} PROPERTIES ${_util_properties}) endforeach() endif() endif() ``` -------------------------------- ### Clone Colopresso Repository Source: https://github.com/colopl/colopresso/blob/main/README.md Initializes the local development environment by cloning the Colopresso repository and its submodules. ```bash git clone --recursive "https://github.com/colopl/colopresso.git" cd colopresso ``` -------------------------------- ### Optimize PNG images with PNGX via CLI Source: https://context7.com/colopl/colopresso/llms.txt Provides various configurations for PNG optimization, including palette quantization, bit reduction, and lossless recompression. These commands are useful for game textures and general web optimization. ```bash colopresso --format=pngx --type=palette256 --max-colors=256 input.png output.png colopresso --format=pngx --quality=85-100 --dither=0.8 input.png output.png colopresso --format=pngx --type=limited --reduce-bits-rgb=4 --reduce-alpha=4 input.png output.png colopresso --format=pngx --type=reduced --max-colors=1024 input.png output.png colopresso --format=pngx --lossless --method=6 input.png output.png colopresso --format=pngx --protect-color=FF0000,00FF00,0000FFFF input.png output.png colopresso --format=pngx --type=palette256 --verbose --gradient-profile --alpha-bleed --threads=4 input.png output.png ``` -------------------------------- ### Configure Colopresso Header Files (CMake) Source: https://github.com/colopl/colopresso/blob/main/CMakeLists.txt This snippet configures and copies header files for Colopresso. It uses CMake's 'configure_file' and 'file(GLOB_RECURSE)' to manage header file generation and inclusion, ensuring correct paths for build and installation. ```cmake configure_file( "${CMAKE_CURRENT_SOURCE_DIR}/library/include/colopresso_config.h.in" "${CMAKE_CURRENT_BINARY_DIR}/include/colopresso_config.h" @ONLY ) file(MAKE_DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}/include") file(GLOB_RECURSE COLOPRESSO_PUBLIC_HEADERS RELATIVE "${CMAKE_CURRENT_SOURCE_DIR}/library/include" "${CMAKE_CURRENT_SOURCE_DIR}/library/include/*.h" ) foreach(_header IN LISTS COLOPRESSO_PUBLIC_HEADERS) get_filename_component(_header_dir "${_header}" DIRECTORY) if(_header_dir) file(MAKE_DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}/include/${_header_dir}") endif() configure_file( "${CMAKE_CURRENT_SOURCE_DIR}/library/include/${_header}" "${CMAKE_CURRENT_BINARY_DIR}/include/${_header}" COPYONLY ) endforeach() set(COLOPRESSO_GENERATED_FILE_HEADER "${CMAKE_CURRENT_BINARY_DIR}/include/colopresso/file.h") if(COLOPRESSO_WITH_FILE_OPS) file(MAKE_DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}/include/colopresso") configure_file( "${CMAKE_CURRENT_SOURCE_DIR}/library/include/colopresso/file.h.in" "${COLOPRESSO_GENERATED_FILE_HEADER}" COPYONLY ) else() file(REMOVE "${COLOPRESSO_GENERATED_FILE_HEADER}") endif() target_include_directories(colopresso PUBLIC $ $ $ ${CMAKE_CURRENT_SOURCE_DIR}/library/src ) ``` -------------------------------- ### Build Python Wheel Source: https://github.com/colopl/colopresso/blob/main/python/README.md Standard command sequence to build a wheel distribution package for the project. ```bash cd python pip install build python -m build --wheel ``` -------------------------------- ### Optimize PNG with Python Source: https://context7.com/colopl/colopresso/llms.txt Demonstrates PNG optimization using lossy techniques like PALETTE256 and RGBA4444. This is useful for reducing file size while maintaining visual quality for game assets or web icons. ```python import colopresso with open("icon.png", "rb") as f: png_data = f.read() # 256-color palette optimization (default mode) config = colopresso.Config( pngx_lossy_enable=True, pngx_lossy_type=colopresso.PngxLossyType.PALETTE256, pngx_lossy_max_colors=256, pngx_lossy_quality_min=85, pngx_lossy_quality_max=100, pngx_lossy_speed=3, # 1-10, lower = better quality pngx_lossy_dither_level=0.8 # 0.0-1.0 ) optimized = colopresso.encode_pngx(png_data, config) # RGBA4444 mode for game textures (prevents banding in 16-bit displays) config = colopresso.Config( pngx_lossy_enable=True, pngx_lossy_type=colopresso.PngxLossyType.LIMITED_RGBA4444, pngx_lossy_reduced_bits_rgb=4, # RGB bits per channel (1-8) pngx_lossy_reduced_alpha_bits=4 # Alpha bits (1-8) ) rgba4444_png = colopresso.encode_pngx(png_data, config) ``` -------------------------------- ### Colopresso Language Detection (JavaScript) Source: https://github.com/colopl/colopresso/blob/main/pages/index.html Detects the user's preferred language based on browser settings. It prioritizes Japanese ('ja') if the language code starts with 'ja', otherwise defaults to English ('en'). This function is essential for initializing the correct language for the i18n configuration. ```javascript const detectLanguage = () => { const lang = (navigator.language || navigator.userLanguage || '').toLowerCase(); if (lang.startsWith('ja')) return 'ja'; return 'en'; }; ``` -------------------------------- ### Manage UI State and Download Logic Source: https://github.com/colopl/colopresso/blob/main/pages/index.html Functions to synchronize UI labels with selected locales, build download URLs based on state parameters, and update the summary display. These functions rely on a global state object and an i18n configuration. ```javascript const syncLanguage = () => { const locale = i18n[state.lang]; document.documentElement.lang = state.lang; $('title').textContent = locale.title; // ... updates DOM elements with localized strings renderOptions(); updateSummary(); }; const buildUrl = () => { const { os, arch, app, use } = state; if (!os || !arch || !app) return null; // Logic to resolve file path from downloadConfig based on OS/Arch/App return downloadConfig.baseUrl + file; }; const updateSummary = () => { const url = buildUrl(); if (url) { $('url').textContent = url; $('download').classList.remove('disabled'); } else { $('download').classList.add('disabled'); } }; ``` -------------------------------- ### Build Python Extension Module with CMake Source: https://github.com/colopl/colopresso/blob/main/python/CMakeLists.txt This CMake script configures the build process for a Python extension module named 'colopresso_python'. It sets up the module to use the Python 3.10+ stable ABI, links it against the Python library, and applies platform-specific settings for libraries and output file suffixes. The compiled module is then installed to a 'colopresso' directory. ```cmake set(COLOPRESSO_PYTHON_ABI_VERSION 0x030a0000) add_library(colopresso_python MODULE "${CMAKE_CURRENT_SOURCE_DIR}/colopresso/_colopresso_ext.c" ) target_compile_definitions(colopresso_python PRIVATE Py_LIMITED_API=${COLOPRESSO_PYTHON_ABI_VERSION} ) target_link_libraries(colopresso_python PRIVATE Python3::Module ) if(UNIX AND NOT APPLE) target_link_libraries(colopresso_python PRIVATE -Wl,--whole-archive colopresso -Wl,--no-whole-archive m ) elseif(APPLE) target_link_libraries(colopresso_python PRIVATE -Wl,-force_load,$ ) else() target_link_libraries(colopresso_python PRIVATE colopresso) endif() target_include_directories(colopresso_python PRIVATE ${COLOPRESSO_ROOT}/library/include ${CMAKE_CURRENT_BINARY_DIR}/include ) set_target_properties(colopresso_python PROPERTIES OUTPUT_NAME "_colopresso" PREFIX "" ) if(WIN32) set_target_properties(colopresso_python PROPERTIES SUFFIX ".pyd") elseif(APPLE) set_target_properties(colopresso_python PROPERTIES SUFFIX ".abi3.so") else() set_target_properties(colopresso_python PROPERTIES SUFFIX ".abi3.so") endif() install( TARGETS colopresso_python LIBRARY DESTINATION colopresso COMPONENT python ) ``` -------------------------------- ### Convert PNG to AVIF with Python Source: https://context7.com/colopl/colopresso/llms.txt Shows how to encode PNG data to AVIF format. Includes configurations for high-quality web images, lossless encoding, fast batch processing, and error handling for cases where AVIF compression is not efficient. ```python import colopresso with open("photo.png", "rb") as f: png_data = f.read() # Basic AVIF conversion with default settings avif_data = colopresso.encode_avif(png_data) # High quality AVIF for web images config = colopresso.Config( avif_quality=80.0, # Quality 0-100 avif_alpha_quality=100, # Alpha channel quality avif_speed=4, # Encoding speed 0-10 (0=best quality, slowest) avif_threads=4 # Use 4 threads for encoding ) avif_hq = colopresso.encode_avif(png_data, config) # Lossless AVIF encoding config = colopresso.Config(avif_lossless=True) avif_lossless = colopresso.encode_avif(png_data, config) # Fast encoding for batch processing config = colopresso.Config( avif_quality=60.0, avif_speed=8, # Faster encoding avif_threads=8 # Maximize parallelism ) avif_fast = colopresso.encode_avif(png_data, config) # Handle case where AVIF is larger than input try: result = colopresso.encode_avif(png_data) with open("output.avif", "wb") as f: f.write(result) except colopresso.ColopressoError as e: if e.code == 9: # Output not smaller print("AVIF not effective for this image, keeping PNG") else: raise ``` -------------------------------- ### Configure Encoder Settings with Config Dataclass Source: https://context7.com/colopl/colopresso/llms.txt Illustrates the creation of a comprehensive configuration object for WebP, AVIF, and PNGX formats. It highlights how to override default settings for specific use cases like web, mobile, or game assets. ```python import colopresso from dataclasses import asdict config = colopresso.Config( webp_quality=80.0, avif_quality=50.0, pngx_level=5, pngx_lossy_enable=True, pngx_lossy_type=colopresso.PngxLossyType.PALETTE256 ) # Create specific configs web_config = colopresso.Config(webp_quality=85.0, webp_method=6) game_config = colopresso.Config(pngx_lossy_type=colopresso.PngxLossyType.LIMITED_RGBA4444) ``` -------------------------------- ### Build Colopresso with Release Configuration (Linux) Source: https://github.com/colopl/colopresso/blob/main/README.md Builds the Colopresso project with a Release configuration on Linux. It enables utilities, tests, and the CLI binary. The build artifacts are placed in the 'build' directory. ```bash rm -rf "build" && cmake -B "build" -DCMAKE_BUILD_TYPE=Release \ -DCOLOPRESSO_USE_UTILS=ON -DCOLOPRESSO_USE_TESTS=ON -DCOLOPRESSO_USE_CLI=ON cmake --build "build" --parallel ctest --test-dir "build" --output-on-failure --parallel ``` -------------------------------- ### Colopresso CLI - Basic Conversion Source: https://context7.com/colopl/colopresso/llms.txt Basic command-line usage for converting images between formats using Colopresso. ```APIDOC ## Colopresso CLI - Basic Conversion ### Description Basic command-line usage for converting images between formats using Colopresso. Format is auto-detected from output extension or specified explicitly. ### Method Command Line Interface ### Endpoint `colopresso` command ### Parameters #### Path Parameters None #### Query Parameters - `--format` (string) - Optional - Explicitly specify the output format (e.g., `webp`, `avif`, `pngx`). - `--version` - Optional - Show version and library information. - `--help` - Optional - Show help with all options. #### Request Body None ### Request Example ```bash # Convert PNG to WebP (format inferred from extension) colopresso input.png output.webp # Convert PNG to AVIF with explicit format colopresso --format=avif input.png output # Convert PNG to optimized PNG colopresso --format=pngx input.png output.png # Show version and library information colopresso --version # Show help with all options colopresso --help ``` ### Response #### Success Response (0) Image converted successfully. Exit code 0. #### Response Example Output file created with the converted image. ``` -------------------------------- ### Optimize PNG with 256-Color Palette Source: https://github.com/colopl/colopresso/blob/main/python/README.md Demonstrates how to perform lossy PNG compression using a 256-color palette. It configures quality settings and dithering levels to achieve significant file size reduction. ```python import colopresso with open("icon.png", "rb") as f: png_data = f.read() config = colopresso.Config( pngx_lossy_enable=True, pngx_lossy_type=colopresso.PngxLossyType.PALETTE256, pngx_lossy_max_colors=256, pngx_lossy_quality_min=85, pngx_lossy_quality_max=100, pngx_lossy_dither_level=0.8 ) optimized = colopresso.encode_pngx(png_data, config) print(f"Original: {len(png_data)} bytes") print(f"Optimized: {len(optimized)} bytes") print(f"Reduction: {(1 - len(optimized)/len(png_data))*100:.1f}%") ``` -------------------------------- ### Encode PNGX Images with Config Source: https://context7.com/colopl/colopresso/llms.txt Demonstrates how to use the Config dataclass to perform lossy and lossless PNGX optimizations. It showcases setting compression levels, metadata stripping, and color reduction strategies. ```python # Reduced RGBA32 mode config = colopresso.Config( pngx_lossy_enable=True, pngx_lossy_type=colopresso.PngxLossyType.REDUCED_RGBA32, pngx_lossy_max_colors=1024 ) reduced_png = colopresso.encode_pngx(png_data, config) # Lossless PNG optimization config = colopresso.Config( pngx_lossy_enable=False, pngx_level=6, pngx_strip_safe=True, pngx_optimize_alpha=True, pngx_threads=4 ) lossless_optimized = colopresso.encode_pngx(png_data, config) ``` -------------------------------- ### Build Options and Configuration (CMake) Source: https://github.com/colopl/colopresso/blob/main/CMakeLists.txt Includes CMake scripts for configuring build options such as threads, debug settings, and SIMD optimizations. It also provides status messages for enabled SIMD types. ```cmake include(cmake/options.cmake) include(cmake/compiler.cmake) colopresso_configure_threads() colopresso_apply_global_threads_compile_options() colopresso_configure_debug() colopresso_configure_simd() if(COLOPRESSO_SIMD_TYPE) message(STATUS "SIMD optimization enabled: ${COLOPRESSO_SIMD_TYPE}") elseif(COLOPRESSO_ENABLE_SIMD) message(STATUS "SIMD optimization enabled but no supported SIMD detected") endif() ``` -------------------------------- ### Retrieve System and Library Information Source: https://context7.com/colopl/colopresso/llms.txt Provides utility functions to query version strings for the library and its dependencies, build information, and thread configuration for parallel processing. ```python import colopresso # Get library versions print(f"colopresso: {colopresso.get_version()}") print(f"libwebp: {colopresso.get_libwebp_version()}") # Thread configuration max_threads = colopresso.get_max_thread_count() config = colopresso.Config( avif_threads=max_threads, pngx_threads=max_threads ) ``` -------------------------------- ### Colopresso CLI - WebP Encoding Options Source: https://context7.com/colopl/colopresso/llms.txt Command-line options for configuring WebP encoding with Colopresso. ```APIDOC ## Colopresso CLI - WebP Encoding Options ### Description Command-line options for configuring WebP encoding with Colopresso, including quality, compression method, and advanced parameters. ### Method Command Line Interface ### Endpoint `colopresso` command ### Parameters #### Path Parameters None #### Query Parameters - `--format` (string) - Required for explicit format - Set to `webp`. - `--quality` (number) - Optional - WebP encoding quality (0-100, default varies). Higher is better quality. - `--method` (number) - Optional - WebP compression method (0-6). Higher is slower but better compression. - `--lossless` (boolean) - Optional - Enable lossless WebP compression. - `--size` (number) - Optional - Target file size in bytes for WebP encoding. - `--sharp-yuv` (boolean) - Optional - Enable sharp YUV conversion for WebP. - `--near-lossless` (number) - Optional - Near-lossless WebP encoding quality (0-100). - `--verbose` (boolean) - Optional - Show verbose output including settings and compression stats. #### Request Body None ### Request Example ```bash # High quality WebP colopresso --format=webp --quality=95 --method=6 input.png output.webp # Lossless WebP colopresso --format=webp --lossless input.png output.webp # WebP with target file size (bytes) colopresso --format=webp --size=50000 input.png output.webp # WebP with sharp YUV conversion colopresso --format=webp --quality=85 --sharp-yuv input.png output.webp # Near-lossless encoding (0-100, higher = closer to lossless) colopresso --format=webp --near-lossless=60 input.png output.webp # Verbose output showing settings and compression stats colopresso --format=webp --quality=80 --verbose input.png output.webp ``` ### Response #### Success Response (0) WebP image encoded successfully. Exit code 0. #### Response Example Output file created with the encoded WebP image. ``` -------------------------------- ### Configure Encoder Settings with C API Source: https://context7.com/colopl/colopresso/llms.txt Shows how to initialize and modify the cpres_config_t structure for different output formats like WebP, AVIF, or protected-color PNG optimization. ```c #include void configure_for_web_images(cpres_config_t *config) { cpres_config_init_defaults(config); config->webp_quality = 80.0f; config->webp_lossless = false; config->webp_method = 6; config->webp_alpha_quality = 100; config->webp_autofilter = true; config->webp_use_sharp_yuv = true; config->avif_quality = 65.0f; config->avif_speed = 4; config->avif_threads = 4; } void configure_for_game_assets(cpres_config_t *config) { cpres_config_init_defaults(config); config->pngx_lossy_enable = true; config->pngx_lossy_type = CPRES_PNGX_LOSSY_TYPE_LIMITED_RGBA4444; config->pngx_lossy_reduced_bits_rgb = 4; config->pngx_lossy_reduced_alpha_bits = 4; config->pngx_level = 6; } void configure_with_protected_colors(cpres_config_t *config, cpres_rgba_color_t *colors, int count) { cpres_config_init_defaults(config); config->pngx_lossy_enable = true; config->pngx_lossy_type = CPRES_PNGX_LOSSY_TYPE_PALETTE256; config->pngx_protected_colors = colors; config->pngx_protected_colors_count = count; } ``` -------------------------------- ### Encode Images to AVIF with Multithreading Source: https://github.com/colopl/colopresso/blob/main/python/README.md Demonstrates how to encode PNG images to AVIF format while utilizing multithreading for improved performance. The configuration object specifies quality, speed, and thread count. ```python import colopresso with open("large_image.png", "rb") as f: png_data = f.read() # Multithreaded high-speed encoding config = colopresso.Config( avif_quality=70.0, avif_speed=6, avif_threads=4 ) avif_data = colopresso.encode_avif(png_data, config) ``` -------------------------------- ### Colopresso Download Configuration (JavaScript) Source: https://github.com/colopl/colopresso/blob/main/pages/index.html Defines the base URL for downloads and a nested structure mapping operating systems, usage types, architectures, and application types to their respective file names. This configuration is used to dynamically construct download links for Colopresso binaries. ```javascript const downloadConfig = { baseUrl: 'https://github.com/colopl/colopresso/releases/latest/download/', files: { Windows: { internal: { amd64: { GUI: "colopresso_colopl_internal_windows_gui_x64.exe", CLI: "colopresso_windows_cli_x64_colopl_internal.exe" }, arm64: { GUI: "colopresso_colopl_internal_windows_gui_arm64.exe", CLI: "colopresso_windows_cli_arm64_colopl_internal.exe" } }, other: { amd64: { GUI: "colopresso_windows_gui_x64.exe", CLI: "colopresso_windows_cli_x64.exe" }, arm64: { GUI: "colopresso_windows_gui_arm64.exe", CLI: "colopresso_windows_cli_arm64.exe" } } }, macOS: { amd64: { GUI: "colopresso_macos_gui_x64.dmg", CLI: "colopresso-cli-macos-intel" }, arm64: { GUI: "colopresso_macos_gui_arm64.dmg", CLI: "colopresso-cli-macos-apple_silicon" } }, Linux: { amd64: { GUI: null, CLI: "colopresso-cli-linux-amd64" }, arm64: { GUI: null, CLI: "colopresso-cli-linux-arm64" } } } }; ``` -------------------------------- ### Colopresso Use Step Visibility Update (JavaScript) Source: https://github.com/colopl/colopresso/blob/main/pages/index.html Dynamically updates the visibility of the 'use' selection step based on the selected operating system. The 'use' options (e.g., 'COLOPL Internal', 'Other') are only shown when the OS is 'Windows'. ```javascript const updateUseStepVisibility = () => { const useStep = $('use-step'); if (!useStep) return; if (state.os === 'Windows') { useStep.classList.remove('hidden'); return; } useStep.classList.add('hidden'); }; ``` -------------------------------- ### Build Colopresso for Chrome Extension Source: https://github.com/colopl/colopresso/blob/main/README.md Builds the project specifically for Chrome extension deployment using Emscripten. ```bash rm -rf "build" && emcmake cmake -B "build" -DCMAKE_BUILD_TYPE=Release -DCOLOPRESSO_CHROME_EXTENSION=ON cmake --build "build" --parallel ```