libwebp Documentation

repository·main·Indexed 25 days ago

https://github.com/webmproject/libwebp

A library and set of tools for encoding and decoding images in the WebP format, supporting both static images and animations. It provides C/C++ APIs for simple and advanced encoding/decoding, command-line tools like cwebp and dwebp, and bindings for Java (JNI), Python (SWIG), and JavaScript/WebAssembly via Emscripten.

Tokens
17.2K
Snippets
33
Records
77
Agent score
77%

What's inside libwebp

  1. Overview of the WebP Codec

    main

    WebP codec is a library designed for encoding and decoding images in the WebP format. It provides two primary ways to use it:

    1. As a Library: Integrate the library into other programs to add native WebP support.
    2. As Command Line Tools: Use the provided tools cwebp for image compression (encoding) and dwebp for image decompression (decoding).

    For detailed information regarding the image format itself, refer to the Google Developers WebP page.

  2. Build libwebp on Unix using makefile.unix

    main

    On platforms with GNU tools (gcc and make) installed, you can perform a simple build that does not perform a system-wide installation. This builds the binaries examples/cwebp and examples/dwebp, along with the static library src/libwebp.a.

    make -f makefile.unix
  3. Convert animated GIF to WebP with gif2webp

    main

    The gif2webp utility converts animated GIF files into animated WebP files.

    Usage

    gif2webp [options] gif_file -o webp_file

    Key Options

    • -lossy: Encode using lossy compression.
    • -mixed: Heuristically pick lossy or lossless compression for each frame.
    • -q <float>: Quality factor (0:small..100:big).
    • -m <int>: Compression method (0=fast, 6=slowest, default=4).
    • -metadata <string>: Comma-separated list of metadata to copy (e.g., all, none, icc, xmp).
    • -mt: Use multi-threading if available.
    • -min_size: Minimize output size.

    Building gif2webp

    Requires libgif development files.

    Using makefile.unix:

    $ make -f makefile.unix examples/gif2webp

    Using autoconf:

    $ ./configure --enable-everything
    $ make
  4. Use the Advanced Encoding API with WebPConfig and WebPPicture

    main

    The advanced API provides full control over encoding parameters via WebPConfig and input data via WebPPicture.

    Workflow:

    1. Configure: Initialize WebPConfig using WebPConfigPreset and tune parameters like sns_strength or filter_sharpness. Validate with WebPValidateConfig.
    2. Prepare Picture: Initialize WebPPicture with WebPPictureInit, set dimensions, and allocate memory with WebPPictureAlloc (or use WebPPictureImportRGB to handle allocation automatically).
    3. Setup Writer: Assign a writer function to pic.writer (e.g., WebPMemoryWriter) to handle the compressed output.
    4. Encode: Call WebPEncode(&config, &pic).
    5. Cleanup: Always call WebPPictureFree(&pic) and clear your writer (e.g., WebPMemoryWriterClear).
    #include <webp/encode.h>
    
    // Setup a config, starting form a preset and tuning some additional
    WebPConfig config;
    if (!WebPConfigPreset(&config, WEBP_PRESET_PHOTO, quality_factor)) {
      return 0;   // version error
    }
    // ... additional tuning
    config.sns_strength = 90;
    config.filter_sharpness = 6;
    config_error = WebPValidateConfig(&config);
    
    // Setup the input data
    WebPPicture pic;
    if (!WebPPictureInit(&pic)) {
      return 0;  // version error
    }
    pic.width = width;
    pic.height = height;
    // allocated picture of dimension width x height
    if (!WebPPictureAlloc(&pic)) {
      return 0;   // memory error
    }
    
    // Set up a byte-output write method. WebPMemoryWriter, for instance.
    WebPMemoryWriter wrt;
    WebPMemoryWriterInit(&wrt);     // initialize 'wrt'
    
    pic.writer = MyFileWriter;
    pic.custom_ptr = my_opaque_structure_to_make_MyFileWriter_work;
    
    // Compress!
    int ok = WebPEncode(&config, &pic);   // ok = 0 => error occurred!
    WebPPictureFree(&pic);  // must be called independently of the 'ok' result.
    
    // output data should have been handled by the writer at that point.
    // -> compressed data is the memory buffer described by wrt.mem / wrt.size
    
    // deallocate the memory used by compressed data
    WebPMemoryWriterClear(&wrt);
  5. Build JNI SWIG bindings for Java

    main

    To build the JNI (Java Native Interface) SWIG bindings, use gcc to compile the wrapper C file into a shared object library. You must include the path to your JDK includes and link against the libwebp library.

    Ensure you replace /path/to/your/jdk/includes with the actual path to your JDK include directory.

     $ gcc -shared -fPIC -fno-strict-aliasing -O2 \
           -I/path/to/your/jdk/includes \
           libwebp_java_wrap.c \
           -lwebp \
           -o libwebp_jni.so
  6. Use the Incremental Decoding API

    main

    When data is being streamed or transmitted progressively, use the WebPIDecoder object to decode chunks as they arrive.

    Workflow:

    1. Initialize Buffer: Set up a WebPDecBuffer and specify the colorspace (e.g., MODE_BGR).
    2. Create Decoder: Create the decoder instance with WebPINewDecoder(&buffer).
    3. Feed Data: Use one of two methods:
      • WebPIAppend(idec, fresh_data, size_of_fresh_data): Appends new bytes to the existing stream.
      • WebPIUpdate(idec, buffer, size_of_transmitted_buffer): Updates the decoder with the new total size of the buffer (useful if the buffer was resized).
    4. Check Status: Functions return VP8_STATUS_OK (done), VP8_STATUS_SUSPENDED (more data needed), or an error code.
    5. Retrieve Pixels: Use WebPIDecGetRGB or WebPIDecGetYUVA to get the partially decoded samples. These return the last displayable pixel row.
    6. Cleanup: Always call WebPIDelete(idec) to release the decoder.
  7. Build libwebp using CMake

    main

    CMake can compile libwebp, various executables (cwebp, dwebp, gif2webp, img2webp, webpinfo), and JS bindings.

    Prerequisites (Debian-like):

    $ sudo apt-get install build-essential cmake

    Build Steps:

    mkdir build && cd build && cmake ../
    make
    make install

    Configuration Options:

    • Enable Executables: Use -DWEBP_BUILD_CWEBP=ON and -DWEBP_BUILD_DWEBP=ON to include specific tools.
    • Windows Unicode Support: Use -DWEBP_UNICODE=ON for Unicode support (requires chcp 65001).

    Integration: In your own CMake project, use:

    find_package(WebP)

    This defines WebP_INCLUDE_DIRS and WebP_LIBRARIES for use in your build configuration.

  8. Generate HTML Docs with Syntax Highlighting

    main

    To generate documentation with syntax highlighting for code blocks (e.g., for the lossless bitstream spec), use kramdown with the CodeRay dependency. This method applies inline CSS styling, so no external stylesheet is required.

    Requirements

    • kramdown 0.13.7 or newer is recommended for optimal syntax highlighting.
    • CodeRay: A dependency of kramdown that is typically installed automatically via RubyGems.

    Command with Syntax Highlighting

    Execute this command from the project root:

    kramdown doc/webp-lossless-bitstream-spec.txt \
      --template doc/template.html \
      -x syntax-coderay --syntax-highlighter coderay \
      --syntax-highlighter-opts "{default_lang: c, line_numbers: , css: style}" \
      > doc/output/webp-lossless-bitstream-spec.html
  9. Use encoding and decoding tools

    main

    The project includes command-line tools for image manipulation.

    • cwebp: Used to compress/encode images into WebP format.
    • dwebp: Used to decompress/decode WebP images.

    Additional tools for viewing WebP image information and handling animations are located in the examples/ directory. For a full list of available tools and their usage, see the tools documentation.

  10. Build the WebP JavaScript decoder

    main

    To compile libwebp into a JavaScript decoder, you must use Emscripten and CMake.

    Prerequisites:

    1. Install the Emscripten SDK following the official instructions.
    2. Ensure the $EMSDK environment variable points to the top-level directory of your Emscripten installation.

    Build Steps:

    1. Configure the project with CMake, enabling the WEBP_BUILD_WEBP_JS option.
    2. Compile using emmake make.

    Upon successful completion, the build process generates webp.js, webp.js.mem, webp_wasm.js, and webp_wasm.wasm.

    cd webp_js && embuilder build sdl2 && \
    emcmake cmake -DWEBP_BUILD_WEBP_JS=ON ../
    
    emmake make
  11. Generate libwebp Container Spec Docs from Text Source

    main

    You can generate HTML documentation for the WebP container specification from text source files using kramdown.

    Prerequisites

    • kramdown: A Ruby gem that must be installed (e.g., via gem install kramdown).
    • RubyGems: Recommended for automatic dependency management.

    Basic HTML Generation

    Run the following command from the project root to convert the container spec text file into an HTML file using the provided template:

    kramdown doc/webp-container-spec.txt --template doc/template.html > doc/output/webp-container-spec.html