webp Go Library

repository·master·Indexed 20 days ago

https://github.com/chai2010/webp

A Go implementation of a WebP JavaScript decoder providing high-performance decoding and encoding capabilities for WebP images. The package includes functions for decoding WebP data via io.Reader or RGB byte slices, encoding to lossless WebP, and extracting image metadata. It also provides utilities for low-level pixel manipulation through PixSlice and custom color models, as well as instructions for building JNI SWIG bindings for Java, Python bindings, and a WebAssembly-based JavaScript decoder using Emscripten.

Tokens
20.4K
Snippets
79
Records
105
Agent score
64%

What's inside webp

  1. Overview of the WebP Codec

    master

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

    1. Library APIs: A set of functions that can be integrated into other programs to add WebP support.
    2. Command Line Tools: Standalone tools for image manipulation:
      • cwebp: Used to compress (encode) images into WebP.
      • dwebp: Used to decompress (decode) WebP images.

    For technical details on the image format itself, refer to the official Google developers documentation.

  2. How incremental decoding works

    master

    When data is being transmitted progressively, use the incremental decoding API. This uses a WebPIDecoder object to maintain state.

    Workflow:

    1. Initialize: Create a buffer (WebPDecBuffer) and initialize it with WebPInitDecBuffer. Set the colorspace (e.g., MODE_BGR).
    2. Create Decoder: Create the decoder instance with WebPINewDecoder(&buffer).
    3. Feed Data: As data arrives, use one of two methods:
      • WebPIAppend(idec, fresh_data, size_of_fresh_data): Appends new bytes.
      • WebPIUpdate(idec, buffer, size_of_transmitted_buffer): Updates the decoder based on the new total size of the buffer.
    4. Check Status: Functions return VP8_STATUS_OK (done) or VP8_STATUS_SUSPENDED (more data needed). Any other value is an error.
    5. Retrieve Pixels: Use WebPIDecGetRGB or WebPIDecGetYUVA to get the partially decoded pixels.
    6. Cleanup: Always call WebPIDelete(idec) to release the decoder.
    WebPDecBuffer buffer;
    WebPInitDecBuffer(&buffer);
    buffer.colorspace = MODE_BGR;
    WebPIDecoder* idec = WebPINewDecoder(&buffer);
    
    // As data arrives:
    WebPIAppend(idec, fresh_data, size_of_fresh_data);
    
    // Check status:
    // VP8_STATUS_OK or VP8_STATUS_SUSPENDED
    
    // Retrieve pixels:
    // WebPIDecGetRGB(idec, ...);
    
    WebPIDelete(idec);
  3. Convert animated GIFs to WebP with gif2webp

    master

    The gif2webp utility (located in examples/) converts animated GIF files to WebP animation.

    Usage:

    gif2webp [options] gif_file -o webp_file

    Options:

    • -h / -help: Show help
    • -lossy: Encode image 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)
    • -min_size: Minimize output size (default: off; uses lossless by default; can be combined with -q, -m, -lossy, or -mixed)
    • -kmin <int>: Min distance between key frames
    • -kmax <int>: Max distance between key frames
    • -f <int>: Filter strength (0=off..100)
    • -metadata <string>: Comma separated list of metadata to copy (valid values: all, none, icc, xmp; default: xmp)
    • -loop_compatibility: Use compatibility mode for Chrome versions prior to M62
    • -mt: Use multi-threading if available
    • -version: Print version number and exit
    • -v: Verbose mode
    • -quiet: Don't print anything

    Building gif2webp: Requires libgif development files. You can build using makefile.unix or autoconf:

    # Using makefile.unix
    make -f makefile.unix examples/gif2webp
    
    # Using autoconf
    ./configure --enable-everything
    make
  4. Build JNI SWIG bindings for Java

    master

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

    Ensure you have the libwebp library installed on your system before compiling.

    $ gcc -shared -fPIC -fno-strict-aliasing -O2 \
           -I/path/to/your/jdk/includes \
           libwebp_java_wrap.c \
           -lwebp \
           -o libwebp_jni.so
  5. Encode images with cwebp

    master

    Use the cwebp tool to convert images (PNG, JPEG, TIFF, or WebP) into WebP format.

    Basic Usage

    To convert an input file with a specific quality factor (0-100, where 100 is best):

    cwebp input.png -q 80 -o output.webp

    Lossless Encoding

    To compress the source without any loss, use the -lossless flag. In this mode, the -q parameter controls the amount of processing time spent to minimize file size rather than visual quality.

    cwebp input.png -lossless -q 75 -o output.webp

    Tuning Visual Quality

    For advanced tuning, use these options in combination:

    • -preset <string>: Sets a default configuration for specific input types (default, photo, picture, drawing, icon, text). Note: This must come first in the command line.
    • -sns <int>: Spatial noise shaping (0-100). Higher values (e.g., 75) improve quality at the cost of larger files by optimizing bit allocation.
    • -f <int>: Filter strength (0-100). Higher values result in smoother highly-compressed areas. Typical values are 20-30.
    • -m <int>: Compression method (0=fast, 6=slowest). Higher values increase encoding time for better quality.
  6. Build libwebp using CMake

    master

    CMake can be used to compile libwebp and various tools including cwebp, dwebp, gif2webp, img2webp, webpinfo, and JS bindings.

    Prerequisites (Debian-like): sudo apt-get install build-essential cmake

    Build Steps:

    1. Create a build directory: mkdir build && cd build.
    2. Run cmake ../.
    3. Run make.
    4. Run make install.

    Configuration Options:

    • Enable specific executables: -DWEBP_BUILD_CWEBP=ON or -DWEBP_BUILD_DWEBP=ON.
    • Windows Unicode support: -DWEBP_UNICODE=ON (requires chcp 65001).

    Integration in CMake projects: Use find_package(WebP) to define WebP_INCLUDE_DIRS and WebP_LIBRARIES.

    mkdir build && cd build && cmake ../
    make
    make install
  7. Build libwebp for MIPS Linux

    master

    To cross-compile for MIPS Linux, you must first add your toolchain to your PATH. The build requires specific MIPS_CFLAGS and MIPS_LDFLAGS depending on whether you are targeting 32-bit or 64-bit architectures.

    32-bit (mips32r5 / p5600):

    • HOST=mips-mti-linux-gnu
    • MIPS_CFLAGS="-O3 -mips32r5 -mabi=32 -mtune=p5600 -mmsa -mfp64 -msched-weight -mload-store-pairs -fPIE"
    • MIPS_LDFLAGS="-mips32r5 -mabi=32 -mmsa -mfp64 -pie"

    64-bit (mips64r6 / i6400):

    • HOST=mips-img-linux-gnu
    • MIPS_CFLAGS="-O3 -mips64r6 -mabi=64 -mtune=i6400 -mmsa -mfp64 -msched-weight -mload-store-pairs -fPIE"
    • MIPS_LDFLAGS="-mips64r6 -mabi=64 -mmsa -mfp64 -pie"
    # Example for 32-bit
    export PATH=$PATH:/path/to/toolchain/bin
    HOST=mips-mti-linux-gnu
    MIPS_CFLAGS="-O3 -mips32r5 -mabi=32 -mtune=p5600 -mmsa -mfp64 -msched-weight -mload-store-pairs -fPIE"
    MIPS_LDFLAGS="-mips32r5 -mabi=32 -mmsa -mfp64 -pie"
    
    ./configure --host=${HOST} --build=`config.guess` \
      CC="${HOST}-gcc -EL" \
      CFLAGS="$MIPS_CFLAGS" \
      LDFLAGS="$MIPS_LDFLAGS"
    make
    make install
  8. Visualize WebP files with vwebp

    master

    The vwebp tool is an OpenGL-based visualization tool that opens a window to display a decoded WebP file.

    Usage

    vwebp in_file [options]

    Keyboard Shortcuts

    • c: Toggle use of color profile
    • b: Toggle background color display
    • i: Overlay file information
    • d: Disable blending & disposal (debug mode)
    • q / Q / ESC: Quit
  9. Decode WebP images with dwebp

    master

    Use the dwebp tool to decode WebP files into various formats. By default, it decodes to PNG.

    Basic Usage

    dwebp input.webp -o output.png

    Supported Output Formats

    You can specify alternative formats using these flags:

    • -pam: Raw RGBA samples as a color PAM
    • -ppm: Raw RGB samples as a color PPM
    • -bmp: Uncompressed BMP format
    • -tiff: Uncompressed TIFF format
    • -pgm: Raw YUV samples as a grayscale PGM file
    • -yuv: Raw YUV samples in flat layout

    Common Options

    • -crop <x> <y> <w> <h>: Crop output with the given rectangle.
    • -resize <w> <h>: Resize output (applied after any cropping).
    • -flip: Flip the output vertically.
    • -mt: Use multi-threading.
    ./dwebp test.webp -ppm -o test.ppm
  10. Generate libwebp Container Spec Docs from Text Source

    master

    To generate HTML documentation from the text source files, you must use kramdown. This process converts .txt specification files into .html files using a provided template.

    Prerequisites

    • kramdown: Installed via rubygem. Installing via Rubygems should automatically satisfy necessary dependencies.
    • CodeRay (Optional): If you want syntax highlighting for code blocks, ensure kramdown is installed with coderay support (handled automatically by Rubygems).
    • Recommended Version: Use kramdown 0.13.7 or newer for optimal syntax highlighting.

    Basic HTML Generation

    Run the following command from the project root to generate the container specification HTML:

    kramdown doc/webp-container-spec.txt --template doc/template.html > doc/output/webp-container-spec.html
  11. Use the Advanced Decoding API for cropping and rescaling

    master

    The Advanced Decoding API allows for on-the-fly cropping and rescaling. This is highly efficient for memory-constrained environments because memory usage scales with the output size rather than the input size.

    Workflow:

    1. Initialize Config: Call WebPInitDecoderConfig(&config).
    2. Get Features: (Optional) Use WebPGetFeatures to inspect the bitstream.
    3. Configure Options: Set config.options.use_scaling = 1 and provide scaled_width and scaled_height. You can also disable fancy upsampling with no_fancy_upsampling.
    4. Configure Output: Specify the output colorspace (e.g., MODE_BGRA) and optionally provide an external buffer via config.output.u.RGBA.rgba to avoid extra allocations.
    5. Decode:
      • For full images: WebPDecode(data, data_size, &config).
      • For incremental/small buffer decoding: Use WebPIDecode to get a WebPIDecoder* and feed it with WebPIAppend.
    6. Cleanup: Call WebPFreeDecBuffer(&config.output) to reclaim memory.
    WebPDecoderConfig config;
    WebPInitDecoderConfig(&config);
    
    // Optional: Get features
    WebPGetFeatures(data, data_size, &config.input);
    
    // Configure scaling/cropping
    config.options.use_scaling = 1;
    config.options.scaled_width = 100;
    config.options.scaled_height = 100;
    
    // Configure output
    config.output.colorspace = MODE_BGRA;
    config.output.is_external_memory = 1;
    config.output.u.RGBA.rgba = my_buffer;
    config.output.u.RGBA.stride = stride;
    config.output.u.RGBA.size = size;
    
    // Decode
    WebPDecode(data, data_size, &config);
    
    // Cleanup
    WebPFreeDecBuffer(&config.output);