### Usage example for bitWriter Source: https://github.com/hugosmits86/nativewebp/blob/main/_autodocs/api-reference/internal-bitwriter.md Demonstrates initializing a bitWriter and writing bits to the buffer. ```go var buf bytes.Buffer w := &bitWriter{Buffer: &buf} w.writeBits(5, 3) // Write 3-bit value 5 (binary: 101) w.writeBits(0xAB, 8) // Write 8-bit value 0xAB w.alignByte() // Align to byte boundary ``` -------------------------------- ### Install nativewebp package Source: https://github.com/hugosmits86/nativewebp/blob/main/README.md Command to add the nativewebp package to your Go project. ```Bash go get github.com/HugoSmits86/nativewebp ``` -------------------------------- ### Configure Encoding Options Source: https://github.com/hugosmits86/nativewebp/blob/main/_autodocs/types.md Examples of using default settings, best compression, and metadata support. ```go // Default settings (no metadata, normal compression) err := nativewebp.Encode(file, img, nil) // With best compression opts := &nativewebp.Options{ CompressionLevel: nativewebp.BestCompression, } err := nativewebp.Encode(file, img, opts) // With metadata support opts := &nativewebp.Options{ UseExtendedFormat: true, CompressionLevel: nativewebp.DefaultCompression, } err := nativewebp.Encode(file, img, opts) ``` -------------------------------- ### Basic Usage of DecodeConfig Source: https://github.com/hugosmits86/nativewebp/blob/main/_autodocs/api-reference/decodeconfig.md Example demonstrating how to open a file and retrieve its configuration metadata. ```go package main import ( "fmt" "log" "os" "github.com/HugoSmits86/nativewebp" ) func main() { // Open a WebP file file, err := os.Open("image.webp") if err != nil { log.Fatalf("Error opening file: %v", err) } defer file.Close() // Read configuration without decoding the entire image config, err := nativewebp.DecodeConfig(file) if err != nil { log.Fatalf("Error reading WebP config: %v", err) } // Use the configuration fmt.Printf("Image dimensions: %dx%d\n", config.Width, config.Height) fmt.Printf("Color model: %v\n", config.ColorModel) } ``` -------------------------------- ### Configure Encoding Options Source: https://github.com/hugosmits86/nativewebp/blob/main/_autodocs/configuration.md Example demonstrating how to initialize and use the Options struct for encoding a single image. ```go package main import ( "image" "log" "os" "github.com/HugoSmits86/nativewebp" ) func main() { // Create or load an image img := image.NewNRGBA(image.Rect(0, 0, 100, 100)) // Configuration with all options specified opts := &nativewebp.Options{ CompressionLevel: nativewebp.BestCompression, UseExtendedFormat: true, } file, err := os.Create("output.webp") if err != nil { log.Fatalf("Error creating file: %v", err) } defer file.Close() err = nativewebp.Encode(file, img, opts) if err != nil { log.Fatalf("Error encoding: %v", err) } } ``` -------------------------------- ### EncodeAll with Custom Compression Source: https://github.com/hugosmits86/nativewebp/blob/main/_autodocs/api-reference/encodeall.md Example showing how to pass custom Options to EncodeAll for specific compression levels. ```go opts := &nativewebp.Options{ CompressionLevel: nativewebp.BestCompression, } file, err := os.Create("animation.webp") if err != nil { log.Fatalf("Error creating file: %v", err) } defer file.Close() err = nativewebp.EncodeAll(file, ani, opts) if err != nil { log.Fatalf("Error encoding animation: %v", err) } ``` -------------------------------- ### EncodeAll Basic Usage Source: https://github.com/hugosmits86/nativewebp/blob/main/_autodocs/api-reference/encodeall.md Example demonstrating how to create an animation with two frames and encode it to a file. ```go package main import ( "image" "image/color" "log" "os" "github.com/HugoSmits86/nativewebp" ) func main() { // Create two frames for animation frame1 := image.NewNRGBA(image.Rect(0, 0, 20, 20)) frame2 := image.NewNRGBA(image.Rect(0, 0, 20, 20)) // Fill frame 1 with red for x := 0; x < 20; x++ { for y := 0; y < 20; y++ { frame1.SetNRGBA(x, y, color.NRGBA{R: 255, G: 0, B: 0, A: 255}) } } // Fill frame 2 with blue for x := 0; x < 20; x++ { for y := 0; y < 20; y++ { frame2.SetNRGBA(x, y, color.NRGBA{R: 0, G: 0, B: 255, A: 255}) } } // Create animation ani := &nativewebp.Animation{ Images: []image.Image{frame1, frame2}, Durations: []uint{100, 100}, // Each frame shows for 100ms Disposals: []uint{0, 0}, // Keep both frames LoopCount: 0, // Loop infinitely BackgroundColor: 0xffffffff, // White background (BGRA) } // Encode animation file, err := os.Create("animation.webp") if err != nil { log.Fatalf("Error creating file: %v", err) } defer file.Close() err = nativewebp.EncodeAll(file, ani, nil) if err != nil { log.Fatalf("Error encoding animation: %v", err) } } ``` -------------------------------- ### Encode with Custom Options Source: https://github.com/hugosmits86/nativewebp/blob/main/_autodocs/api-reference/encode.md Example of applying specific compression levels and enabling extended format support. ```go // Encode with best compression opts := &nativewebp.Options{ CompressionLevel: nativewebp.BestCompression, UseExtendedFormat: true, } file, err := os.Create("output.webp") if err != nil { log.Fatalf("Error creating file: %v", err) } defer file.Close() err = nativewebp.Encode(file, img, opts) if err != nil { log.Fatalf("Error encoding image: %v", err) } ``` -------------------------------- ### Encode a WebP animation Source: https://github.com/hugosmits86/nativewebp/blob/main/README.md Example showing how to configure and encode an animation sequence using nativewebp.Animation. ```Go file, err := os.Create(name) if err != nil { log.Fatalf("Error creating file %s: %v", name, err) } defer file.Close() ani := nativewebp.Animation{ Images: []image.Image{ frame1, frame2, }, Durations: []uint { 100, 100, }, Disposals: []uint { 0, 0, }, LoopCount: 0, BackgroundColor: 0xffffffff, } err = nativewebp.EncodeAll(file, &ani, nil) if err != nil { log.Fatalf("Error encoding WebP animation: %v", err) } ``` -------------------------------- ### Checking Image Dimensions Before Loading Source: https://github.com/hugosmits86/nativewebp/blob/main/_autodocs/api-reference/decodeconfig.md Example showing how to validate image dimensions against constraints before proceeding with a full decode. ```go package main import ( "fmt" "log" "os" "github.com/HugoSmits86/nativewebp" ) func main() { file, err := os.Open("image.webp") if err != nil { log.Fatalf("Error opening file: %v", err) } defer file.Close() // Check dimensions before loading full image config, err := nativewebp.DecodeConfig(file) if err != nil { log.Fatalf("Error reading WebP config: %v", err) } if config.Width > 4000 || config.Height > 4000 { log.Fatalf("Image too large: %dx%d", config.Width, config.Height) } fmt.Printf("Image is safe to decode: %dx%d\n", config.Width, config.Height) } ``` -------------------------------- ### Memory-Safe Decoding Source: https://github.com/hugosmits86/nativewebp/blob/main/_autodocs/api-reference/decodeignorealpflag.md Example of checking file size before decoding to ensure it stays within the 256 MiB memory limit. ```go package main import ( "fmt" "log" "os" "github.com/HugoSmits86/nativewebp" ) func main() { file, err := os.Open("large_image.webp") if err != nil { log.Fatalf("Error opening file: %v", err) } defer file.Close() // Check file size before decoding fileInfo, err := file.Stat() if err != nil { log.Fatalf("Error getting file info: %v", err) } if fileInfo.Size() > 200*1024*1024 { log.Fatalf("File too large: %d bytes exceeds practical limit", fileInfo.Size()) } // Safe to decode img, err := nativewebp.DecodeIgnoreAlphaFlag(file) if err != nil { log.Fatalf("Error decoding WebP: %v", err) } fmt.Printf("Successfully decoded: %dx%d\n", img.Bounds().Dx(), img.Bounds().Dy()) } ``` -------------------------------- ### Import nativewebp Source: https://github.com/hugosmits86/nativewebp/blob/main/_autodocs/quick-reference.md Include the package in your Go project. ```go import "github.com/HugoSmits86/nativewebp" ``` -------------------------------- ### Encode with options Source: https://github.com/hugosmits86/nativewebp/blob/main/_autodocs/INDEX.md Configure encoding settings such as compression level. ```go opts := &nativewebp.Options{ CompressionLevel: nativewebp.BestCompression, } err := nativewebp.Encode(file, img, opts) ``` -------------------------------- ### Define Options struct Source: https://github.com/hugosmits86/nativewebp/blob/main/_autodocs/types.md Defines the configuration settings for WebP encoding. ```go type Options struct { UseExtendedFormat bool CompressionLevel CompressionLevel } ``` -------------------------------- ### Configure WebP Compression Levels Source: https://github.com/hugosmits86/nativewebp/blob/main/_autodocs/configuration.md Set the compression level to optimize for speed, file size, or a balance of both. ```go opts := &nativewebp.Options{ CompressionLevel: nativewebp.BestSpeed, // Level 0 } ``` ```go opts := &nativewebp.Options{ CompressionLevel: nativewebp.BestCompression, // Level 6 } ``` ```go opts := &nativewebp.Options{ CompressionLevel: nativewebp.DefaultCompression, // Level 4 } // Or simply pass nil err := nativewebp.Encode(file, img, nil) ``` -------------------------------- ### Create and Encode Image Source: https://github.com/hugosmits86/nativewebp/blob/main/_autodocs/quick-reference.md Demonstrates creating an NRGBA image, populating pixels, and encoding to a file. ```go // Create NRGBA image (most efficient) img := image.NewNRGBA(image.Rect(0, 0, width, height)) // Set pixels for x := 0; x < width; x++ { for y := 0; y < height; y++ { img.SetNRGBA(x, y, color.NRGBA{R: 255, G: 0, B: 0, A: 255}) } } // Encode file, _ := os.Create("output.webp") defer file.Close() nativewebp.Encode(file, img, nil) ``` -------------------------------- ### Use CompressionLevel with Encode Source: https://github.com/hugosmits86/nativewebp/blob/main/_autodocs/types.md Demonstrates applying a specific compression level to the encoding options. ```go opts := &nativewebp.Options{ CompressionLevel: nativewebp.BestCompression, } err := nativewebp.Encode(file, img, opts) ``` -------------------------------- ### Encode with All Options Source: https://github.com/hugosmits86/nativewebp/blob/main/_autodocs/quick-reference.md Configures compression levels and extended format support using the Options struct. ```go opts := &nativewebp.Options{ CompressionLevel: nativewebp.BestCompression, UseExtendedFormat: true, } file, _ := os.Create("output.webp") defer file.Close() nativewebp.Encode(file, img, opts) ``` -------------------------------- ### Implement bitWriter in encoding pipeline Source: https://github.com/hugosmits86/nativewebp/blob/main/_autodocs/api-reference/internal-bitwriter.md Demonstrates the standard usage pattern for bitWriter during VP8L frame encoding, including header writing and byte alignment. ```go s := &bitWriter{Buffer: b} writeBitStreamHeader(s, rgba.Bounds(), !rgba.Opaque()) // ... apply transforms and write transform metadata ... s.alignByte() if b.Len() % 2 != 0 { b.Write([]byte{0x00}) } ``` -------------------------------- ### Encode an Image with Default Settings Source: https://github.com/hugosmits86/nativewebp/blob/main/_autodocs/api-reference/encode.md Basic implementation for creating a 10x10 NRGBA image and saving it as a WebP file. ```go package main import ( "image" "image/color" "log" "os" "github.com/HugoSmits86/nativewebp" ) func main() { // Create a simple 10x10 image with red pixels img := image.NewNRGBA(image.Rect(0, 0, 10, 10)) for x := 0; x < 10; x++ { for y := 0; y < 10; y++ { img.SetNRGBA(x, y, color.NRGBA{R: 255, G: 0, B: 0, A: 255}) } } // Create output file file, err := os.Create("output.webp") if err != nil { log.Fatalf("Error creating file: %v", err) } defer file.Close() // Encode with default compression err = nativewebp.Encode(file, img, nil) if err != nil { log.Fatalf("Error encoding image: %v", err) } } ``` -------------------------------- ### Registering WebP with the image package Source: https://github.com/hugosmits86/nativewebp/blob/main/_autodocs/quick-reference.md Import the package with an underscore to register the WebP decoder, allowing standard image.Decode to process WebP files. ```go import _ "github.com/HugoSmits86/nativewebp" import "image" // Now image.Decode recognizes "webp" format img, format, _ := image.Decode(reader) // format == "webp" ``` -------------------------------- ### Handle Problematic VP8L with Fallback Source: https://github.com/hugosmits86/nativewebp/blob/main/_autodocs/api-reference/decodeignorealpflag.md Demonstrates a robust decoding strategy by attempting a standard decode first and falling back to DecodeIgnoreAlphaFlag if it fails. ```go package main import ( "fmt" "log" "os" "github.com/HugoSmits86/nativewebp" "image" ) func main() { file, err := os.Open("problematic_vp8l.webp") if err != nil { log.Fatalf("Error opening file: %v", err) } defer file.Close() // Try standard decode first, fall back to flag-ignoring decode var img image.Image file.Seek(0, 0) img, err = nativewebp.Decode(file) if err != nil { // If standard decode fails, try ignoring alpha flag file.Seek(0, 0) img, err = nativewebp.DecodeIgnoreAlphaFlag(file) if err != nil { log.Fatalf("Error decoding WebP with both methods: %v", err) } fmt.Println("Successfully decoded with DecodeIgnoreAlphaFlag") } // Use the decoded image nrgba, ok := img.(*image.NRGBA) if ok { c := nrgba.NRGBAAt(0, 0) fmt.Printf("Pixel at (0,0): R=%d G=%d B=%d A=%d\n", c.R, c.G, c.B, c.A) } } ``` -------------------------------- ### Package types Source: https://github.com/hugosmits86/nativewebp/blob/main/_autodocs/quick-reference.md Core structures and types used for configuring encoding and animation. ```go // Compression level enum type CompressionLevel int // Encoding options type Options struct { UseExtendedFormat bool // Enable VP8X container CompressionLevel CompressionLevel // 0-6 } // Animation configuration type Animation struct { Images []image.Image // Frames Durations []uint // ms per frame Disposals []uint // 0=keep, 1=clear LoopCount uint16 // 0=infinite BackgroundColor uint32 // BGRA format } ``` -------------------------------- ### Check Image Size Before Loading Source: https://github.com/hugosmits86/nativewebp/blob/main/_autodocs/quick-reference.md Uses DecodeConfig to inspect image dimensions before performing a full decode. ```go file, _ := os.Open("image.webp") defer file.Close() config, _ := nativewebp.DecodeConfig(file) if config.Width > 4000 || config.Height > 4000 { log.Fatalf("Image too large") } // Safe to decode file.Seek(0, 0) img, _ := nativewebp.Decode(file) ``` -------------------------------- ### Implement Decode with Fallback Source: https://github.com/hugosmits86/nativewebp/blob/main/_autodocs/errors.md Attempt standard decoding and provide a fallback method using alternative flags if the initial attempt fails. ```go package main import ( "fmt" "log" "os" "github.com/HugoSmits86/nativewebp" ) func decodeFallback(filename string) error { file, err := os.Open(filename) if err != nil { return fmt.Errorf("cannot open file: %w", err) } defer file.Close() // Try standard decode first img, err := nativewebp.Decode(file) if err == nil { fmt.Printf("Decoded successfully: %dx%d\n", img.Bounds().Dx(), img.Bounds().Dy()) return nil } // If standard decode fails, try with alpha flag ignored file.Seek(0, 0) img, err = nativewebp.DecodeIgnoreAlphaFlag(file) if err != nil { return fmt.Errorf("both decode methods failed: %w", err) } fmt.Printf("Decoded with flag workaround: %dx%d\n", img.Bounds().Dx(), img.Bounds().Dy()) return nil } func main() { err := decodeFallback("image.webp") if err != nil { log.Fatalf("Error: %v", err) } } ``` -------------------------------- ### Perform Basic Error Handling for Encoding Source: https://github.com/hugosmits86/nativewebp/blob/main/_autodocs/errors.md Check for errors during file creation and the encoding process to ensure robust file operations. ```go package main import ( "log" "os" "github.com/HugoSmits86/nativewebp" "image" ) func main() { img := image.NewNRGBA(image.Rect(0, 0, 100, 100)) file, err := os.Create("output.webp") if err != nil { log.Fatalf("Cannot create file: %v", err) } defer file.Close() err = nativewebp.Encode(file, img, nil) if err != nil { log.Fatalf("Encoding failed: %v", err) } } ``` -------------------------------- ### Encode pixel data with Huffman compression Source: https://github.com/hugosmits86/nativewebp/blob/main/_autodocs/api-reference/complete-signatures.md Encodes pixel data using 5 Huffman codes and prefix encoding. ```go func writeImageData(w *bitWriter, pixels []color.NRGBA, width, height int, isRecursive bool, colorBits int) ``` -------------------------------- ### Encode an image to WebP Source: https://github.com/hugosmits86/nativewebp/blob/main/README.md Basic implementation for encoding an image using the nativewebp encoder. ```Go file, err := os.Create(name) if err != nil { log.Fatalf("Error creating file %s: %v", name, err) } defer file.Close() err = nativewebp.Encode(file, img, nil) if err != nil { log.Fatalf("Error encoding image to WebP: %v", err) } ``` -------------------------------- ### Write Huffman codes with writeCode Source: https://github.com/hugosmits86/nativewebp/blob/main/_autodocs/api-reference/internal-bitwriter.md Writes a Huffman code to the stream, applying bit reversal to match WebP wire format requirements. ```go code := huffmanCode{ Symbol: 42, Bits: 0b101, Depth: 3, } w.writeCode(code) // Writes 3 bits: 0b101 (reversed) ``` -------------------------------- ### Define CompressionLevel Constants Source: https://github.com/hugosmits86/nativewebp/blob/main/_autodocs/configuration.md Predefined constants for setting the compression effort level. ```go const ( BestSpeed CompressionLevel = 0 // Fastest, least compression DefaultCompression CompressionLevel = 4 // Balanced (recommended) BestCompression CompressionLevel = 6 // Slowest, most compression ) ``` -------------------------------- ### Display File Organization Structure Source: https://github.com/hugosmits86/nativewebp/blob/main/_autodocs/README.md Visual representation of the documentation directory structure. ```text output/ ├── INDEX.md (master index) ├── README.md (this file) ├── quick-reference.md (quick lookup) ├── types.md (type definitions) ├── configuration.md (configuration reference) ├── errors.md (error handling) ├── architecture.md (system design) └── api-reference/ ├── encode.md ├── encodeall.md ├── decode.md ├── decodeconfig.md ├── decodeignorealpflag.md ├── internal-bitwriter.md └── complete-signatures.md ``` -------------------------------- ### Define CompressionLevel Source: https://github.com/hugosmits86/nativewebp/blob/main/_autodocs/types.md Defines the compression effort levels for WebP encoding. ```go type CompressionLevel int const ( BestSpeed CompressionLevel = 0 DefaultCompression CompressionLevel = 4 BestCompression CompressionLevel = 6 ) ``` -------------------------------- ### Encode an image Source: https://github.com/hugosmits86/nativewebp/blob/main/_autodocs/INDEX.md Perform basic encoding of an image to a file. ```go err := nativewebp.Encode(file, img, nil) ``` -------------------------------- ### Define Huffman Constants in Go Source: https://github.com/hugosmits86/nativewebp/blob/main/_autodocs/api-reference/complete-signatures.md Constants governing Huffman coding parameters and image size limits. ```go const ( NUM_HUFFMAN_BITS = 3 MIN_HUFFMAN_BITS = 2 MAX_HUFFMAN_BITS = 10 // (2 + (1 << 3) - 1) MAX_HUFF_IMAGE_SIZE = 2600 ) ``` -------------------------------- ### Access pixel data from a decoded WebP image Source: https://github.com/hugosmits86/nativewebp/blob/main/_autodocs/api-reference/decode.md Demonstrates how to cast the decoded image to *image.NRGBA to perform pixel-level operations. ```go package main import ( "fmt" "log" "os" "github.com/HugoSmits86/nativewebp" "image" ) func main() { file, err := os.Open("image.webp") if err != nil { log.Fatalf("Error opening file: %v", err) } defer file.Close() img, err := nativewebp.Decode(file) if err != nil { log.Fatalf("Error decoding WebP: %v", err) } // Cast to NRGBA for pixel access nrgba, ok := img.(*image.NRGBA) if !ok { log.Fatalf("Unexpected image type") } // Access pixel at (0, 0) c := nrgba.NRGBAAt(0, 0) fmt.Printf("Pixel at (0,0): R=%d G=%d B=%d A=%d\n", c.R, c.G, c.B, c.A) } ``` -------------------------------- ### nativewebp.EncodeAll Source: https://github.com/hugosmits86/nativewebp/blob/main/_autodocs/quick-reference.md Encodes an animation sequence into a single WebP file. ```APIDOC ## func EncodeAll(w io.Writer, a *Animation, o *Options) error ### Description Encodes an animation structure containing multiple frames and timing information into a WebP file. ### Parameters - **w** (io.Writer) - The destination writer. - **a** (*Animation) - The animation configuration containing frames, durations, and loop settings. - **o** (*Options) - Optional encoding settings. ``` -------------------------------- ### nativewebp.DecodeConfig Source: https://github.com/hugosmits86/nativewebp/blob/main/_autodocs/quick-reference.md Retrieves image configuration without decoding the full pixel data. ```APIDOC ## func DecodeConfig(r io.Reader) (image.Config, error) ### Description Reads the WebP header to return image dimensions and color model information. ``` -------------------------------- ### Encode with Validation Source: https://github.com/hugosmits86/nativewebp/blob/main/_autodocs/quick-reference.md Validates image presence and dimensions before creating a file and encoding it. ```go func encodeWebP(filename string, img image.Image) error { if img == nil { return fmt.Errorf("image is nil") } bounds := img.Bounds() if bounds.Dx() < 1 || bounds.Dy() < 1 { return fmt.Errorf("invalid dimensions: %dx%d", bounds.Dx(), bounds.Dy()) } file, err := os.Create(filename) if err != nil { return err } defer file.Close() return nativewebp.Encode(file, img, nil) } ``` -------------------------------- ### Convert image to VP8L bitstream Source: https://github.com/hugosmits86/nativewebp/blob/main/_autodocs/api-reference/complete-signatures.md Converts an image to a VP8L bitstream with specified compression method. ```go func writeBitStream(img image.Image, method int) (*bytes.Buffer, bool, error) ``` -------------------------------- ### Decode WebP images Source: https://github.com/hugosmits86/nativewebp/blob/main/_autodocs/quick-reference.md Decode files into image.Image objects, retrieve configuration metadata, or use specific decoding flags. ```go file, _ := os.Open("image.webp") defer file.Close() img, err := nativewebp.Decode(file) // Get image config without decoding file.Seek(0, 0) config, err := nativewebp.DecodeConfig(file) fmt.Printf("%dx%d\n", config.Width, config.Height) // Decode with alpha flag workaround file.Seek(0, 0) img, err := nativewebp.DecodeIgnoreAlphaFlag(file) ``` -------------------------------- ### Decode image metadata Source: https://github.com/hugosmits86/nativewebp/blob/main/_autodocs/INDEX.md Extract configuration and metadata from a WebP file without decoding the full image. ```go config, err := nativewebp.DecodeConfig(file) ``` -------------------------------- ### Align bitstream to byte boundary with alignByte Source: https://github.com/hugosmits86/nativewebp/blob/main/_autodocs/api-reference/internal-bitwriter.md Pads the current bit buffer with zeros to reach the next byte boundary, typically used before finalizing the stream. ```go var buf bytes.Buffer w := &bitWriter{Buffer: &buf} w.writeBits(3, 4) // Write 4 bits (BitBufferSize = 4) w.alignByte() // Pad to byte boundary (BitBufferSize = 8) // Buffer now contains one complete byte ``` -------------------------------- ### DecodeConfig Function Signature Source: https://github.com/hugosmits86/nativewebp/blob/main/_autodocs/api-reference/decodeconfig.md The function signature for reading WebP configuration from an io.Reader. ```go func DecodeConfig(r io.Reader) (image.Config, error) ``` -------------------------------- ### Write Huffman Code Source: https://github.com/hugosmits86/nativewebp/blob/main/_autodocs/api-reference/complete-signatures.md Writes a huffmanCode structure to the bitWriter. ```go func (w *bitWriter) writeCode(code huffmanCode) ``` -------------------------------- ### Define Animation struct Source: https://github.com/hugosmits86/nativewebp/blob/main/_autodocs/types.md The core structure for configuring WebP animation frames and their properties. ```go type Animation struct { Images []image.Image Durations []uint Disposals []uint LoopCount uint16 BackgroundColor uint32 } ``` -------------------------------- ### Animation with 3 Frames Source: https://github.com/hugosmits86/nativewebp/blob/main/_autodocs/quick-reference.md Encodes an animated WebP sequence with specified frame durations and disposal methods. ```go frames := []image.Image{frame1, frame2, frame3} durations := []uint{100, 150, 100} // milliseconds disposals := []uint{0, 0, 1} // 0=keep, 1=clear ani := &nativewebp.Animation{ Images: frames, Durations: durations, Disposals: disposals, LoopCount: 0, // Loop forever BackgroundColor: 0x000000ff, // Black background } file, _ := os.Create("anim.webp") defer file.Close() nativewebp.EncodeAll(file, ani, nil) ``` -------------------------------- ### func EncodeAll(w io.Writer, ani *Animation, o *Options) error Source: https://github.com/hugosmits86/nativewebp/blob/main/_autodocs/api-reference/encodeall.md Encodes an animated WebP sequence to an io.Writer with support for frame timing, disposal methods, looping, and background color. ```APIDOC ## func EncodeAll(w io.Writer, ani *Animation, o *Options) error ### Description Encodes an animated WebP sequence to an io.Writer. It supports frame timing, disposal methods, looping, and background color settings. ### Parameters - **w** (io.Writer) - Required - The destination writer where the encoded WebP animation will be written. - **ani** (*Animation) - Required - Pointer to Animation containing frames and animation settings. - **o** (*Options) - Optional - Pointer to Options containing encoding settings. If nil, uses DefaultCompression. ### Returns - **error** - Returns an error if encoding fails, if animation parameters are invalid, or if writing to the io.Writer encounters an issue. Returns nil on success. ### Behavior - Encodes a sequence of frames as a WebP animation using the VP8X container. - Each frame is individually compressed using VP8L (lossless WebP). - All slices in Animation (Images, Durations, Disposals) must have equal length. - Supports infinite looping (LoopCount = 0). ``` -------------------------------- ### EncodeAll Source: https://github.com/hugosmits86/nativewebp/blob/main/_autodocs/quick-reference.md Encodes an animated sequence of images into a single WebP file. ```APIDOC ## EncodeAll ### Signature `func EncodeAll(w io.Writer, ani *Animation, opts *Options) error` ### Description Encodes an animated WebP sequence. The Animation struct contains the frames, durations, and disposal methods for the animation. ``` -------------------------------- ### Encode animated WebP Source: https://github.com/hugosmits86/nativewebp/blob/main/_autodocs/quick-reference.md Use EncodeAll to save an Animation struct containing multiple frames and timing data. ```go ani := &nativewebp.Animation{ Images: []image.Image{frame1, frame2}, Durations: []uint{100, 100}, Disposals: []uint{0, 0}, LoopCount: 0, // 0 = infinite BackgroundColor: 0xffffffff, // White BGRA } file, _ := os.Create("animation.webp") defer file.Close() err := nativewebp.EncodeAll(file, ani, nil) ``` -------------------------------- ### Encode static images Source: https://github.com/hugosmits86/nativewebp/blob/main/_autodocs/quick-reference.md Use Encode to save an image.Image to a file, optionally providing compression settings. ```go file, _ := os.Create("output.webp") defer file.Close() // Encode with default settings (no options) err := nativewebp.Encode(file, img, nil) // Encode with options opts := &nativewebp.Options{ CompressionLevel: nativewebp.BestCompression, } err := nativewebp.Encode(file, img, opts) ``` -------------------------------- ### func Encode(w io.Writer, img image.Image, o *Options) error Source: https://github.com/hugosmits86/nativewebp/blob/main/_autodocs/api-reference/encode.md Encodes an image to WebP lossless (VP8L) format and writes it to the provided io.Writer. Supports optional configuration via the Options struct. ```APIDOC ## func Encode(w io.Writer, img image.Image, o *Options) error ### Description Writes the provided image to an io.Writer in WebP lossless (VP8L) format. The function supports optional encoding settings and handles internal conversion to NRGBA format if necessary. ### Parameters - **w** (io.Writer) - Required - The destination writer where the encoded WebP image will be written. - **img** (image.Image) - Required - The input image to be encoded. Only image.NRGBA format is supported. - **o** (*Options) - Optional - Pointer to Options containing encoding settings. If nil, uses DefaultCompression. ### Returns - **error** - Returns an error if encoding fails or if writing to the io.Writer encounters an issue. Returns nil on success. ### Behavior - Encodes the image using VP8L (lossless WebP). - If Options.UseExtendedFormat is true, wraps the VP8L frame inside a VP8X container to enable metadata support. - Image dimensions must be at least 1x1 pixel and no larger than 16384x16384. ### Errors - "image is nil": Triggered if img parameter is nil. - "invalid image size": Triggered if dimensions are less than 1 or exceed 16384. - "unsupported image format": Triggered if image is not in NRGBA format and cannot be converted. ``` -------------------------------- ### CompressionLevel Constants Source: https://github.com/hugosmits86/nativewebp/blob/main/_autodocs/api-reference/complete-signatures.md Constants defining the available compression levels for WebP encoding. ```APIDOC ## CompressionLevel Constants ### Description These constants define the compression level settings for the WebP encoder, ranging from speed-optimized to compression-optimized. ### Constants - **BestSpeed** (CompressionLevel) - 0 - **DefaultCompression** (CompressionLevel) - 4 - **BestCompression** (CompressionLevel) - 6 ``` -------------------------------- ### func DecodeConfig(r io.Reader) (image.Config, error) Source: https://github.com/hugosmits86/nativewebp/blob/main/_autodocs/api-reference/decodeconfig.md Reads image configuration (metadata) from a WebP file without performing a full decode. ```APIDOC ## func DecodeConfig(r io.Reader) (image.Config, error) ### Description Reads image configuration (metadata) from a WebP file without performing a full decode. This is more efficient than a full decode when only image dimensions are needed. ### Parameters - **r** (io.Reader) - Required - The source io.Reader containing the WebP encoded image. ### Returns - **image.Config** - Contains the image's dimensions (Width, Height) and color model. - **error** - Returns an error if the configuration cannot be retrieved, such as invalid format, unsupported features, or corrupt header data. ### Example ```go file, err := os.Open("image.webp") if err != nil { log.Fatal(err) } defer file.Close() config, err := nativewebp.DecodeConfig(file) if err != nil { log.Fatal(err) } fmt.Printf("Dimensions: %dx%d", config.Width, config.Height) ``` ``` -------------------------------- ### DecodeConfig Source: https://github.com/hugosmits86/nativewebp/blob/main/_autodocs/api-reference/complete-signatures.md Reads the configuration metadata from WebP data. ```APIDOC ## func DecodeConfig(r io.Reader) (image.Config, error) ### Description Extracts image metadata such as width, height, and color model from the provided WebP data reader. ### Parameters - **r** (io.Reader) - Source reader containing WebP data ### Returns - **image.Config** - Image metadata - **error** - Returns an error if the configuration cannot be read ``` -------------------------------- ### nativewebp.Encode Source: https://github.com/hugosmits86/nativewebp/blob/main/_autodocs/quick-reference.md Encodes an image to WebP format with optional compression settings. ```APIDOC ## func Encode(w io.Writer, m image.Image, o *Options) error ### Description Encodes an image to the provided writer in WebP format. If options are nil, default settings are used. ### Parameters - **w** (io.Writer) - The destination writer. - **m** (image.Image) - The source image to encode. - **o** (*Options) - Optional encoding settings including CompressionLevel and UseExtendedFormat. ``` -------------------------------- ### nativewebp.Decode Source: https://github.com/hugosmits86/nativewebp/blob/main/_autodocs/quick-reference.md Decodes a WebP image from an io.Reader. ```APIDOC ## func Decode(r io.Reader) (image.Image, error) ### Description Decodes a WebP image from the provided reader and returns an image.Image interface. ``` -------------------------------- ### Write VP8L bitstream header Source: https://github.com/hugosmits86/nativewebp/blob/main/_autodocs/api-reference/complete-signatures.md Writes the VP8L frame header including signature, dimensions, and alpha flag. ```go func writeBitStreamHeader(w *bitWriter, bounds image.Rectangle, hasAlpha bool) ``` -------------------------------- ### EncodeAll Function Signature Source: https://github.com/hugosmits86/nativewebp/blob/main/_autodocs/api-reference/encodeall.md The function signature for encoding an animated WebP sequence. ```go func EncodeAll(w io.Writer, ani *Animation, o *Options) error ``` -------------------------------- ### Validate Image Before Encoding Source: https://github.com/hugosmits86/nativewebp/blob/main/_autodocs/errors.md Verify image dimensions and type before encoding to prevent runtime errors or unexpected performance degradation. ```go package main import ( "fmt" "log" "os" "github.com/HugoSmits86/nativewebp" "image" ) func encodeIfValid(w *os.File, img image.Image) error { if img == nil { return fmt.Errorf("image is nil") } bounds := img.Bounds() if bounds.Dx() < 1 || bounds.Dy() < 1 { return fmt.Errorf("invalid image dimensions: %dx%d", bounds.Dx(), bounds.Dy()) } if bounds.Dx() > 16384 || bounds.Dy() > 16384 { return fmt.Errorf("image too large: %dx%d exceeds 16384 limit", bounds.Dx(), bounds.Dy()) } // Check if image is NRGBA; if not, it will be converted (slower) if _, ok := img.(*image.NRGBA); !ok { log.Println("Warning: image will be converted to NRGBA internally") } return nativewebp.Encode(w, img, nil) } func main() { img := image.NewNRGBA(image.Rect(0, 0, 100, 100)) file, err := os.Create("output.webp") if err != nil { log.Fatalf("Cannot create file: %v", err) } defer file.Close() err = encodeIfValid(file, img) if err != nil { log.Fatalf("Encoding failed: %v", err) } } ``` -------------------------------- ### Encode Source: https://github.com/hugosmits86/nativewebp/blob/main/_autodocs/api-reference/complete-signatures.md Encodes an image.Image into WebP format and writes it to the provided io.Writer. ```APIDOC ## func Encode(w io.Writer, img image.Image, o *Options) error ### Description Encodes an input image into WebP format and writes the result to the specified writer. The input image is converted to NRGBA if necessary. ### Parameters - **w** (io.Writer) - Destination writer for encoded WebP data - **img** (image.Image) - Input image to encode - **o** (*Options) - Encoding options; pass nil for default settings ### Returns - **error** - Returns an error if validation or encoding fails ``` -------------------------------- ### Convert CompressionLevel to Method Number Source: https://github.com/hugosmits86/nativewebp/blob/main/_autodocs/api-reference/complete-signatures.md Converts a CompressionLevel constant to an internal method number between 0 and 6. ```go func getMethodLevel(lvl CompressionLevel) int ``` -------------------------------- ### func Decode(r io.Reader) (image.Image, error) Source: https://github.com/hugosmits86/nativewebp/blob/main/_autodocs/api-reference/decode.md Reads a WebP image from an io.Reader and returns it as an image.Image. This function supports both lossy (VP8) and lossless (VP8L) WebP formats and preserves the alpha channel. ```APIDOC ## func Decode(r io.Reader) (image.Image, error) ### Description Reads a WebP image from an io.Reader and returns it as an image.Image. The returned image can be cast to *image.NRGBA for pixel-level access. ### Parameters - **r** (io.Reader) - Required - The source io.Reader containing the WebP encoded image data. ### Returns - **image.Image** - The decoded image. - **error** - Returns an error if decoding fails (e.g., invalid format, unsupported feature, or invalid bitstream). ### Example ```go import "github.com/HugoSmits86/nativewebp" file, _ := os.Open("image.webp") img, err := nativewebp.Decode(file) ``` ``` -------------------------------- ### Encode image data with transforms Source: https://github.com/hugosmits86/nativewebp/blob/main/_autodocs/api-reference/complete-signatures.md Encodes image data using optional transforms and Huffman compression. ```go func writeBitStreamData(w *bitWriter, img image.Image, colorBits, histoBits, transBits int, transforms [4]bool) error ``` -------------------------------- ### Align BitWriter to Byte Boundary Source: https://github.com/hugosmits86/nativewebp/blob/main/_autodocs/api-reference/complete-signatures.md Aligns the bitWriter to the next byte boundary. ```go func (w *bitWriter) alignByte() ``` -------------------------------- ### Write Bytes to BitWriter Source: https://github.com/hugosmits86/nativewebp/blob/main/_autodocs/api-reference/complete-signatures.md Writes a slice of bytes to the bitWriter. ```go func (w *bitWriter) writeBytes(values []byte) ``` -------------------------------- ### Write byte slices with writeBytes Source: https://github.com/hugosmits86/nativewebp/blob/main/_autodocs/api-reference/internal-bitwriter.md Writes a slice of bytes to the bitstream, processing each byte as 8 bits. ```go var buf bytes.Buffer w := &bitWriter{Buffer: &buf} w.writeBytes([]byte("VP8L")) // Write "VP8L" header w.writeBytes([]byte{0x00, 0x01, 0x02}) ``` -------------------------------- ### Decode WebP with Alpha Flag Source: https://github.com/hugosmits86/nativewebp/blob/main/_autodocs/api-reference/decodeignorealpflag.md Basic usage of DecodeIgnoreAlphaFlag to decode a VP8X WebP file that has the alpha flag set. ```go package main import ( "fmt" "log" "os" "github.com/HugoSmits86/nativewebp" ) func main() { // Open a VP8X WebP file with VP8L and alpha flag set file, err := os.Open("image_with_alpha.webp") if err != nil { log.Fatalf("Error opening file: %v", err) } defer file.Close() // Decode using flag-ignoring function img, err := nativewebp.DecodeIgnoreAlphaFlag(file) if err != nil { log.Fatalf("Error decoding WebP: %v", err) } // Use the decoded image bounds := img.Bounds() fmt.Printf("Image dimensions: %dx%d\n", bounds.Dx(), bounds.Dy()) } ``` -------------------------------- ### Write Through BitWriter Source: https://github.com/hugosmits86/nativewebp/blob/main/_autodocs/api-reference/complete-signatures.md Flushes or writes through the current bitWriter state. ```go func (w *bitWriter) writeThrough() ``` -------------------------------- ### Apply LZ77 matching and color caching Source: https://github.com/hugosmits86/nativewebp/blob/main/_autodocs/api-reference/complete-signatures.md Processes pixel data using LZ77 matching and color caching to produce encoded symbols. ```go func encodeImageData(pixels []color.NRGBA, width, height, colorBits int) []int ``` -------------------------------- ### Flush bits to buffer with writeThrough Source: https://github.com/hugosmits86/nativewebp/blob/main/_autodocs/api-reference/internal-bitwriter.md Flushes accumulated bits to the buffer as complete bytes. This is called automatically by writeBits when the buffer size reaches 8 bits. ```go var buf bytes.Buffer w := &bitWriter{Buffer: &buf} w.BitBuffer = 0xFF // Store 8 bits: 11111111 w.BitBufferSize = 8 w.writeThrough() // Flushes byte 0xFF to buf // After: BitBuffer = 0, BitBufferSize = 0, buf contains [0xFF] ``` -------------------------------- ### Decode a WebP image in Go Source: https://github.com/hugosmits86/nativewebp/blob/main/_autodocs/api-reference/decode.md Basic usage of the Decode function to read a WebP file and retrieve its dimensions. ```go package main import ( "fmt" "log" "os" "github.com/HugoSmits86/nativewebp" ) func main() { // Open a WebP file file, err := os.Open("image.webp") if err != nil { log.Fatalf("Error opening file: %v", err) } defer file.Close() // Decode the WebP image img, err := nativewebp.Decode(file) if err != nil { log.Fatalf("Error decoding WebP: %v", err) } // Use the decoded image bounds := img.Bounds() fmt.Printf("Image dimensions: %dx%d\n", bounds.Dx(), bounds.Dy()) } ``` -------------------------------- ### nativewebp.DecodeIgnoreAlphaFlag Source: https://github.com/hugosmits86/nativewebp/blob/main/_autodocs/quick-reference.md Decodes a WebP image while ignoring the alpha flag. ```APIDOC ## func DecodeIgnoreAlphaFlag(r io.Reader) (image.Image, error) ### Description Decodes the image using a workaround to ignore the alpha channel flag. ``` -------------------------------- ### Decode WebP data Source: https://github.com/hugosmits86/nativewebp/blob/main/_autodocs/api-reference/complete-signatures.md Decodes WebP data from an io.Reader into an image.Image. ```go func Decode(r io.Reader) (image.Image, error) ``` -------------------------------- ### BackgroundColor bit format Source: https://github.com/hugosmits86/nativewebp/blob/main/_autodocs/types.md Bit layout for the 32-bit BGRA BackgroundColor field. ```text Bits 24-31: Blue channel (0-255) Bits 16-23: Green channel (0-255) Bits 8-15: Red channel (0-255) Bits 0-7: Alpha channel (0-255) ``` -------------------------------- ### func DecodeIgnoreAlphaFlag(r io.Reader) (image.Image, error) Source: https://github.com/hugosmits86/nativewebp/blob/main/_autodocs/api-reference/decodeignorealpflag.md Decodes a WebP image from an io.Reader while ignoring the VP8X alpha flag. This is useful for VP8L images that include transparency but are rejected by standard decoders due to the alpha flag metadata. ```APIDOC ## func DecodeIgnoreAlphaFlag(r io.Reader) (image.Image, error) ### Description Decodes a WebP image while ignoring the VP8X alpha flag, allowing VP8L images with transparency to be decoded correctly. The function reads the entire image into memory, with a limit of 256 MiB. ### Parameters - **r** (io.Reader) - Required - The source io.Reader containing the WebP encoded image. ### Returns - **image.Image** - The decoded image. - **error** - An error if decoding fails, such as invalid format, unsupported feature, I/O error, or if the file exceeds the 256 MiB limit. ``` -------------------------------- ### Define writeBits method signature Source: https://github.com/hugosmits86/nativewebp/blob/main/_autodocs/api-reference/internal-bitwriter.md The writeBits method appends a specified number of bits to the bit stream. ```go func (w *bitWriter) writeBits(value uint64, n int) ``` -------------------------------- ### DecodeConfig Source: https://github.com/hugosmits86/nativewebp/blob/main/_autodocs/quick-reference.md Reads the dimensions and configuration of a WebP image without performing a full decode. ```APIDOC ## DecodeConfig ### Signature `func DecodeConfig(r io.Reader) (image.Config, error)` ### Description Parses the WebP header to retrieve image dimensions and color model information without decoding the pixel data. ``` -------------------------------- ### Define bitWriter structure Source: https://github.com/hugosmits86/nativewebp/blob/main/_autodocs/api-reference/internal-bitwriter.md The bitWriter structure manages the bit-stream buffer and bit accumulation state. ```go type bitWriter struct { Buffer *bytes.Buffer BitBuffer uint64 BitBufferSize int } ``` -------------------------------- ### Convert Image to NRGBA Pixel Array Source: https://github.com/hugosmits86/nativewebp/blob/main/_autodocs/api-reference/complete-signatures.md Converts an image.Image to a row-major NRGBA pixel array. Returns an error if the format is unsupported. ```go func flatten(img image.Image) ([]color.NRGBA, error) ``` -------------------------------- ### Encode animation frames Source: https://github.com/hugosmits86/nativewebp/blob/main/_autodocs/api-reference/complete-signatures.md Encodes animation frames including timing metadata and disposal settings. ```go func writeFrames(ani *Animation, method int) (*bytes.Buffer, bool, error) ``` -------------------------------- ### Encode Function Signature Source: https://github.com/hugosmits86/nativewebp/blob/main/_autodocs/api-reference/encode.md The standard function signature for encoding an image to a WebP stream. ```go func Encode(w io.Writer, img image.Image, o *Options) error ```