### Install golang.org/x/image Source: https://github.com/golang/image/blob/master/_autodocs/README.md Use 'go get' to install the package. This command fetches and installs the specified package and any packages that it depends on. ```bash go get golang.org/x/image ``` -------------------------------- ### Example: Setting Compression for TIFF Encoding Source: https://github.com/golang/image/blob/master/_autodocs/05-tiff-package.md Demonstrates how to create TIFF options with a specific compression method (Deflate) and use them during encoding. ```go opts := &tiff.Options{Compression: tiff.Deflate} tiff.Encode(file, img, opts) ``` -------------------------------- ### Example: Drawing Text with Drawer Source: https://github.com/golang/image/blob/master/_autodocs/03-font-package.md Demonstrates how to initialize and use the font.Drawer to render a string onto a destination image. Ensure necessary packages are imported. ```go import ( "image" "image/color" "image/draw" "golang.org/x/image/font" "golang.org/x/image/font/basicfont" "golang.org/x/image/math/fixed" ) func drawText(dst draw.Image) { d := &font.Drawer{ Dst: dst, Src: image.NewUniform(color.White), Face: basicfont.Face7x13, Dot: fixed.Point26_6{X: fixed.Int26_6(10 << 6), Y: fixed.Int26_6(20 << 6)}, } d.DrawString("Hello, World!") } ``` -------------------------------- ### Using SrcMask for Glyph Rendering Source: https://github.com/golang/image/blob/master/_autodocs/02-draw-package.md Example showing how to use SrcMask for rendering glyphs with a uniform color, applying an alpha mask from a separate image. ```go // Draw glyph at location dp with uniform color Copy(dst, dp, image.NewUniform(color.White), image.Rect(0, 0, glyphWidth, glyphHeight), Src, &Options{ SrcMask: glyphAtlas, SrcMaskP: glyphOffset, }) ``` -------------------------------- ### Using DstMask as a Clip Region Source: https://github.com/golang/image/blob/master/_autodocs/02-draw-package.md Example demonstrating how to limit repainting to a specific rectangular area using the DstMask option. ```go // Limit repainting to a dirty rectangle Copy(dst, dp, src, sr, op, &Options{ DstMask: dirtyRect, DstMaskP: image.Point{0, 0}, }) ``` -------------------------------- ### Examples of Format and Unsupported Errors Source: https://github.com/golang/image/blob/master/_autodocs/12-types-and-configuration.md Illustrates how to create and use FormatError and UnsupportedError for specific image format issues, such as invalid byte order or unsupported compression. ```go tiff.FormatError("invalid byte order") tiff.UnsupportedError("unsupported compression method") bmp.ErrUnsupported ``` -------------------------------- ### Typical TIFF Usage Pattern in Go Source: https://github.com/golang/image/blob/master/_autodocs/05-tiff-package.md A comprehensive example showing the typical workflow for reading, checking dimensions, decoding, and optionally re-encoding a TIFF image with compression. ```go package main import ( "log" "os" "golang.org/x/image/tiff" ) func main() { // 1. Check image size file, err := os.Open("photo.tiff") if err != nil { log.Fatal(err) } config, err := tiff.DecodeConfig(file) if err != nil { log.Fatal(err) } // 2. Verify dimensions if config.Width > 10000 || config.Height > 10000 { log.Fatal("Image too large") } // 3. Decode full image file.Seek(0, 0) img, err := tiff.Decode(file) if err != nil { log.Fatal(err) } file.Close() // 4. Optionally re-encode with compression outFile, err := os.Create("compressed.tiff") if err != nil { log.Fatal(err) } defer outFile.Close() opts := &tiff.Options{Compression: tiff.Deflate} if err := tiff.Encode(outFile, img, opts); err != nil { log.Fatal(err) } } ``` -------------------------------- ### 2D Graphics Transformation Example Source: https://github.com/golang/image/blob/master/_autodocs/09-math-float-package.md Demonstrates a typical 2D graphics pattern using Affine transformations for scaling and translation. This snippet shows how to apply a transformation to an image. ```go import ( "golang.org/x/image/draw" "golang.org/x/image/math/f32" ) func transformDraw(dst draw.Image, src image.Image, width, height int) { // Create transformation: scale 2x, translate to center m := f32.Aff3{ 2, 0, float32(width) / 4, // scale x, translate x 0, 2, float32(height) / 4, // scale y, translate y } // Apply transformation draw.ApproxBiLinear.Transform( dst, f64.Aff3{float64(m[0]), float64(m[1]), float64(m[2]), float64(m[3]), float64(m[4]), float64(m[5])}, src, src.Bounds(), draw.Src, nil, ) } ``` -------------------------------- ### Example Usage of Draw Function Source: https://github.com/golang/image/blob/master/_autodocs/02-draw-package.md Demonstrates copying a source image to a destination image at a specified position using the Draw function. ```go // Copy src to dst at position (10, 20) draw.Draw(dst, image.Rect(10, 20, 110, 120), src, image.Point{0, 0}, draw.Src) ``` -------------------------------- ### Rasterizer.MoveTo Source: https://github.com/golang/image/blob/master/_autodocs/08-vector-package.md Starts a new sub-path at the specified point (x, y). This method implicitly ends any currently active path and sets the starting point for a new one. ```APIDOC ## Rasterizer.MoveTo ### Description Starts a new sub-path at the specified point. This implicitly ends any current path. ### Signature ```go func (z *Rasterizer) MoveTo(x, y float32) ``` ### Parameters #### Path Parameters - **x** (float32) - X coordinate - **y** (float32) - Y coordinate ``` -------------------------------- ### Minimal BMP Image Decode Example Source: https://github.com/golang/image/blob/master/_autodocs/README.md A basic Go program to open a BMP image file and decode it using the bmp package. Ensure the 'image.bmp' file exists in the same directory. ```go package main import ( "os" "golang.org/x/image/bmp" ) func main() { file, _ := os.Open("image.bmp") img, _ := bmp.Decode(file) _ = img } ``` -------------------------------- ### Example of Int26_6 Multiplication Source: https://github.com/golang/image/blob/master/_autodocs/06-math-fixed-package.md Demonstrates the correct way to multiply two Int26_6 fixed-point numbers using the Mul method to ensure proper scaling and avoid incorrect results from direct multiplication. ```go x := fixed.I(2) // 2.0 y := fixed.I(3) // 3.0 z := x.Mul(y) // 6.0 (correct) // x * y would give wrong scaling ``` -------------------------------- ### Case-Insensitive Color Selection Example Source: https://github.com/golang/image/blob/master/_autodocs/10-colornames-package.md Demonstrates selecting a color using the `Name` function, which handles case-insensitivity automatically. Contrasts this with direct map access, which requires a lowercase key. ```Go userInput := "DarkSlateGray" color, ok := colornames.Name(userInput) // Case is handled automatically by Name() // vs. direct map access (requires lowercase) color := colornames.Map[strings.ToLower(userInput)] ``` -------------------------------- ### Example: Handling TIFF Errors Source: https://github.com/golang/image/blob/master/_autodocs/05-tiff-package.md Demonstrates how to handle specific TIFF errors like FormatError and UnsupportedError using a type switch after decoding a TIFF file. ```go img, err := tiff.Decode(file) if err != nil { switch err.(type) { case tiff.FormatError: log.Fatal("Invalid TIFF file format") case tiff.UnsupportedError: log.Fatal("TIFF uses unsupported feature") default: log.Fatal(err) } } ``` -------------------------------- ### Common Transformations Source: https://github.com/golang/image/blob/master/_autodocs/09-math-float-package.md Provides examples for creating identity matrices, translation, scaling, rotation, and composition of 2D affine transformations using the f32 package. ```APIDOC ## Common Transformations ### Identity Matrix ```go identity := f32.Mat2{1, 0, 0, 1} // 2D identity identity := f32.Mat3{1, 0, 0, 0, 1, 0, 0, 0, 1} // 3D identity identity := f32.Mat4{1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1} // 4D ``` ### Translation (2D Affine) ```go func translate(tx, ty float32) f32.Aff3 { return f32.Aff3{1, 0, tx, 0, 1, ty} } ``` ### Scaling (2D Affine) ```go func scale(sx, sy float32) f32.Aff3 { return f32.Aff3{sx, 0, 0, 0, sy, 0} } ``` ### Rotation (2D Affine) ```go import "math" func rotate(angleRad float32) f32.Aff3 { c := float32(math.Cos(float64(angleRad))) s := float32(math.Sin(float64(angleRad))) return f32.Aff3{c, -s, 0, s, c, 0} } ``` ### Composition ```go // Apply translation then rotation trans := translate(10, 20) rot := rotate(math.Pi / 4) // 45 degrees combined := rot.Mul(trans) // Note: right-to-left order point := f32.Vec2{5, 5} transformed := combined.MulVec2(point) ``` ``` -------------------------------- ### TIFF Encoding Options Source: https://github.com/golang/image/blob/master/_autodocs/12-types-and-configuration.md Specifies the Options struct for TIFF encoding, allowing configuration of compression. Example shows how to set Deflate compression and use it with tiff.Encode. ```go type Options struct { Compression Compression } // Usage: opts := &tiff.Options{Compression: tiff.Deflate} tiff.Encode(file, img, opts) ``` -------------------------------- ### TIFF Decode Example Source: https://github.com/golang/image/blob/master/_autodocs/05-tiff-package.md Decodes a TIFF image from a seekable source. Requires io.ReaderAt. Ensure the file is opened and closed properly. ```go package main import ( "log" "os" "golang.org/x/image/tiff" ) func main() { file, err := os.Open("image.tiff") if err != nil { log.Fatal(err) } defer file.Close() img, err := tiff.Decode(file) if err != nil { log.Fatal(err) } bounds := img.Bounds() width := bounds.Dx() height := bounds.Dy() _ = width _ = height } ``` -------------------------------- ### TIFF DecodeConfig Example Source: https://github.com/golang/image/blob/master/_autodocs/05-tiff-package.md Reads TIFF header and directory information without decoding pixel data. Useful for checking image dimensions and resources before full decoding. Requires io.ReaderAt. ```go file, err := os.Open("image.tiff") if err != nil { log.Fatal(err) } defer file.Close() config, err := tiff.DecodeConfig(file) if err != nil { log.Fatal(err) } fmt.Printf("TIFF image: %dx%d\n", config.Width, config.Height) if config.Width > 10000 || config.Height > 10000 { log.Fatal("Image too large") } ``` -------------------------------- ### Typical WebP Image Decoding and Usage Pattern Source: https://github.com/golang/image/blob/master/_autodocs/04-webp-package.md This snippet demonstrates a robust pattern for decoding WebP images. It first decodes the configuration to check dimensions, preventing excessive memory allocation for large images, before proceeding to decode the full image and then using it, for example, by scaling. ```go package main import ( "image" "log" "os" "golang.org/x/image/webp" "golang.org/x/image/draw" "golang.org/x/image/math/f64" ) func main() { // 1. Check image size file, err := os.Open("photo.webp") if err != nil { log.Fatal(err) } config, err := webp.DecodeConfig(file) if err != nil { log.Fatal(err) } // 2. Verify dimensions before decoding if config.Width > 8000 || config.Height > 8000 { log.Fatal("Image too large") } // 3. Decode full image file.Seek(0, 0) img, err := webp.Decode(file) if err != nil { log.Fatal(err) } file.Close() // 4. Use image (e.g., scale it) dst := image.NewRGBA(image.Rect(0, 0, 320, 240)) draw.ApproxBiLinear.Transform(dst, f64.Aff3{320, 0, 0, 0, 240, 0}, img, img.Bounds(), draw.Src, nil) } ``` -------------------------------- ### Draw with Named Colors Source: https://github.com/golang/image/blob/master/_autodocs/13-usage-examples.md Illustrates how to use predefined named colors from the 'colornames' package to draw colored rectangles. This example iterates through a list of color names and applies them to segments of an image. ```go package main import ( "image" "image/draw" "os" "golang.org/x/image/bmp" "golang.org/x/image/colornames" ) func main() { // Create image dst := image.NewRGBA(image.Rect(0, 0, 200, 100)) // Draw with named colors colors := []string{"red", "green", "blue", "yellow", "cyan", "magenta"} rectWidth := 200 / len(colors) for i, colorName := range colors { c, ok := colornames.Name(colorName) if !ok { println("Color not found:", colorName) continue } x := i * rectWidth rect := image.Rect(x, 0, x+rectWidth, 100) draw.Draw(dst, rect, image.NewUniform(c), image.Point{}, draw.Src) } // Save file, _ := os.Create("colors.bmp") bmp.Encode(file, dst) file.Close() } ``` -------------------------------- ### Rasterizer.Close Source: https://github.com/golang/image/blob/master/_autodocs/08-vector-package.md Closes the current sub-path by drawing a line from the current point back to the starting point of the sub-path (the most recent MoveTo point). The current point is updated to this starting point. ```APIDOC ## Rasterizer.Close ### Description Closes the current sub-path by drawing a line from the current point back to the most recent MoveTo point. Updates current point to the MoveTo point. ### Signature ```go func (z *Rasterizer) Close() ``` ``` -------------------------------- ### Import and Use f64.Vec2 Source: https://github.com/golang/image/blob/master/_autodocs/09-math-float-package.md Demonstrates importing the f64 package and performing vector addition with f64.Vec2. ```go import "golang.org/x/image/math/f64" func example() { v := f64.Vec2{1.5, 2.5} u := f64.Vec2{3.0, 4.0} w := v.Add(u) // {4.5, 6.5} } ``` -------------------------------- ### Get height of Rectangle26_6 Source: https://github.com/golang/image/blob/master/_autodocs/06-math-fixed-package.md Calculates the height of a rectangle by subtracting Min.Y from Max.Y. Returns an Int26_6. ```go func (r Rectangle26_6) Dy() Int26_6 ``` -------------------------------- ### Create Identity Matrices (f32) Source: https://github.com/golang/image/blob/master/_autodocs/09-math-float-package.md Shows how to create identity matrices for 2x2, 3x3, and 4x4 using the f32 package. ```go identity := f32.Mat2{1, 0, 0, 1} // 2D identity identity := f32.Mat3{1, 0, 0, 0, 1, 0, 0, 0, 1} // 3D identity identity := f32.Mat4{1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1} // 4D ``` -------------------------------- ### Get width of Rectangle26_6 Source: https://github.com/golang/image/blob/master/_autodocs/06-math-fixed-package.md Calculates the width of a rectangle by subtracting Min.X from Max.X. Returns an Int26_6. ```go func (r Rectangle26_6) Dx() Int26_6 ``` -------------------------------- ### Create f32.Vec2 instances Source: https://github.com/golang/image/blob/master/_autodocs/09-math-float-package.md Demonstrates creating instances of f32.Vec2 with specific values or default zero values. ```go v := f32.Vec2{1, 2} // x=1, y=2 zero := f32.Vec2{} // {0, 0} ``` -------------------------------- ### TIFF Image Metadata Decoding Source: https://github.com/golang/image/blob/master/_autodocs/README.md Get metadata (configuration) of a TIFF image from an io.ReaderAt without decoding the entire image. ```go import "golang.org/x/image/tiff" func DecodeTIFFConfig(r io.ReaderAt) (image.Config, error) { return tiff.DecodeConfig(r) } ``` -------------------------------- ### WebP Image Metadata Decoding Source: https://github.com/golang/image/blob/master/_autodocs/README.md Get metadata (configuration) of a WebP image from an io.Reader without decoding the entire image. ```go import "golang.org/x/image/webp" func DecodeWebPConfig(r io.Reader) (image.Config, error) { return webp.DecodeConfig(r) } ``` -------------------------------- ### Use Helper for Fixed-Point Creation Source: https://github.com/golang/image/blob/master/_autodocs/03-font-package.md Demonstrates using the `fixed.P` helper function for a more concise way to create fixed.Point26_6 instances from integer pixel coordinates. ```go point := fixed.P(10, 20) ``` -------------------------------- ### BMP Image Metadata Decoding Source: https://github.com/golang/image/blob/master/_autodocs/README.md Get metadata (configuration) of a BMP image from an io.Reader without decoding the entire image. ```go import "golang.org/x/image/bmp" func DecodeBMPConfig(r io.Reader) (image.Config, error) { return bmp.DecodeConfig(r) } ``` -------------------------------- ### Get Named Color Source: https://github.com/golang/image/blob/master/_autodocs/00-index.md Retrieves a color value from SVG 1.1 named colors. The colornames package is required for this functionality. ```go import "golang.org/x/image/colornames" c, ok := colornames.Name("darkslategray") uniform := image.NewUniform(c) ``` -------------------------------- ### Import Patterns for Image Packages Source: https://github.com/golang/image/blob/master/_autodocs/README.md Demonstrates common import patterns for the golang.org/x/image package. The first block shows auto-registration of format decoders, while the second imports specific drawing and math utility packages. ```go // Auto-register format decoders import ( _ "golang.org/x/image/bmp" _ "golang.org/x/image/tiff" _ "golang.org/x/image/webp" ) // Use packages import ( "golang.org/x/image/draw" "golang.org/x/image/font" "golang.org/x/image/vector" "golang.org/x/image/colornames" "golang.org/x/image/math/fixed" ) ``` -------------------------------- ### Create Thumbnail from WebP Source: https://github.com/golang/image/blob/master/_autodocs/13-usage-examples.md Demonstrates decoding a WebP image, creating a 100x100 thumbnail using approximate bilinear scaling, and saving it as a BMP file. This is useful for generating previews of images. Requires 'image', 'os', 'golang.org/x/image/bmp', 'golang.org/x/image/draw', and 'golang.org/x/image/webp'. ```go package main import ( "image" "os" "golang.org/x/image/bmp" "golang.org/x/image/draw" "golang.org/x/image/webp" ) func main() { // Decode WebP file, _ := os.Open("image.webp") img, _ := webp.Decode(file) file.Close() // Create 100x100 thumbnail bounds := img.Bounds() thumbSize := image.Rect(0, 0, 100, 100) thumb := image.NewRGBA(thumbSize) // Scale with good quality draw.ApproxBiLinear.Scale(thumb, thumbSize, img, bounds, draw.Src, nil) // Save as BMP out, _ := os.Create("thumbnail.bmp") bmp.Encode(out, thumb) out.Close() } ``` -------------------------------- ### f64 Package Usage Source: https://github.com/golang/image/blob/master/_autodocs/09-math-float-package.md Demonstrates importing and using the f64 package, which provides identical interfaces to f32 but with 64-bit floating-point precision for vectors and matrices. ```APIDOC ## Package f64 (64-bit float) ### Types Identical to f32, using float64: - **Vec2, Vec3, Vec4:** 2D/3D/4D vectors - **Mat2, Mat3, Mat4:** 2×2, 3×3, 4×4 matrices - **Aff3:** 2×3 affine matrix ### Import and Usage ```go import "golang.org/x/image/math/f64" func example() { v := f64.Vec2{1.5, 2.5} u := f64.Vec2{3.0, 4.0} w := v.Add(u) // {4.5, 6.5} } ``` ``` -------------------------------- ### Define FourCC Chunk Identifier Source: https://github.com/golang/image/blob/master/_autodocs/11-riff-package.md A FourCC is a 4-byte chunk identifier used in RIFF format. Examples include 'RIFF', 'WEBP', and 'VP8 '. ```go type FourCC [4]byte ``` -------------------------------- ### Position text using font.Drawer with fixed-point coordinates Source: https://github.com/golang/image/blob/master/_autodocs/06-math-fixed-package.md Demonstrates positioning text using the font.Drawer with sub-pixel precision. Shows initialization with direct fixed-point values and using the helper function P(). ```go import ( "golang.org/x/image/font" "golang.org/x/image/math/fixed" ) // Position text at pixel (10, 20) with sub-pixel precision drawer := &font.Drawer{ Dot: fixed.Point26_6{ X: fixed.Int26_6(10 << 6), // 10.0 Y: fixed.Int26_6(20 << 6), // 20.0 }, } // Or using helpers: drawer.Dot = fixed.P(10, 20) ``` -------------------------------- ### Import Image Packages Source: https://github.com/golang/image/blob/master/_autodocs/00-index.md Import necessary image packages for decoding, encoding, and manipulation. ```go import "golang.org/x/image/bmp" import "golang.org/x/image/ccitt" import "golang.org/x/image/colornames" import "golang.org/x/image/draw" import "golang.org/x/image/font" import "golang.org/x/image/font/basicfont" import "golang.org/x/image/font/opentype" import "golang.org/x/image/font/plan9font" import "golang.org/x/image/font/sfnt" import "golang.org/x/image/math/f32" import "golang.org/x/image/math/f64" import "golang.org/x/image/math/fixed" import "golang.org/x/image/riff" import "golang.org/x/image/tiff" import "golang.org/x/image/vector" import "golang.org/x/image/webp" ``` -------------------------------- ### Decode BMP File Source: https://github.com/golang/image/blob/master/_autodocs/13-usage-examples.md Opens a BMP file, decodes its configuration to get dimensions, and then decodes the entire image. Ensure the BMP file exists in the same directory. ```go package main import ( "fmt" "os" "golang.org/x/image/bmp" ) func main() { // Open file file, err := os.Open("image.bmp") if err != nil { panic(err) } defer file.Close() // Check size first config, err := bmp.DecodeConfig(file) if err != nil { panic(err) } fmt.Printf("Image: %dx%d\n", config.Width, config.Height) // Decode image file.Seek(0, 0) img, err := bmp.Decode(file) if err != nil { panic(err) } bounds := img.Bounds() _ = bounds } ``` -------------------------------- ### Define a line using Point26_6 for vector graphics Source: https://github.com/golang/image/blob/master/_autodocs/06-math-fixed-package.md Illustrates creating line endpoints with sub-pixel precision using Point26_6. Shows manual calculation of fixed-point values. ```go // Create a line from (100.5, 200.25) to (300.75, 400.5) from := fixed.Point26_6{ X: fixed.Int26_6(100<<6 + 32), // 100.5 Y: fixed.Int26_6(200<<6 + 16), // 200.25 } to := fixed.Point26_6{ X: fixed.Int26_6(300<<6 + 48), // 300.75 Y: fixed.Int26_6(400<<6 + 32), // 400.5 } ``` -------------------------------- ### ccitt.NewWriter Source: https://github.com/golang/image/blob/master/_autodocs/07-ccitt-package.md Creates a new writer that compresses data using CCITT compression. Write uncompressed 1-bit scanline data, get back compressed output. ```APIDOC ## NewWriter ### Description Creates a new writer that compresses data using CCITT compression. Write uncompressed 1-bit scanline data, get back compressed output. ### Method func NewWriter(group Group, order MSBFirst, width int, height int) *Writer ### Parameters #### Path Parameters - **group** (Group) - Required - Compression standard (Group3 or Group4) - **order** (MSBFirst) - Required - Bit order (true for most significant bit first) - **width** (int) - Required - Number of pixels per scanline - **height** (int) - Required - Number of scanlines ### Return Type *Writer ### Example Usage ```go package main import ( "golang.org/x/image/ccitt" ) func main() { // Create writer for Group4 compression // width=800, height=600 writer := ccitt.NewWriter(ccitt.Group4, true, 800, 600) // Write uncompressed scanlines scanline := make([]byte, 100) // 800 pixels = 100 bytes for y := 0; y < 600; y++ { // Fill scanline with data (1 bit per pixel) copy(scanline, [...]) writer.Write(scanline) } // Get compressed data compressed := writer.Close() } ``` ``` -------------------------------- ### Read WebP File with RIFF Source: https://github.com/golang/image/blob/master/_autodocs/11-riff-package.md Demonstrates how to open a file, create a RIFF reader, and iterate through chunks to identify VP8, VP8L, ALPH, and VP8X chunks in a WebP file. Handles potential errors during file opening and RIFF parsing. ```go package main import ( "fmt" "io" "os" "golang.org/x/image/riff" ) func readWebP(filename string) error { file, err := os.Open(filename) if err != nil { return err } defer file.Close() formType, reader, err := riff.NewReader(file) if err != nil { return err } if string(formType[:]) != "WEBP" { return fmt.Errorf("not a WebP file") } var vp8Chunk, vp8lChunk bool var alphaData []byte for { chunkID, chunkLen, chunkData, err := reader.Next() if err == io.EOF { break } if err != nil { return err } switch string(chunkID[:]) { case "VP8 ": fmt.Printf("Found VP8 chunk: %d bytes\n", chunkLen) vp8Chunk = true io.ReadFull(chunkData, make([]byte, chunkLen)) case "VP8L": fmt.Printf("Found VP8L chunk: %d bytes\n", chunkLen) vp8lChunk = true io.ReadFull(chunkData, make([]byte, chunkLen)) case "ALPH": fmt.Printf("Found ALPH chunk: %d bytes\n", chunkLen) alphaData = make([]byte, chunkLen) io.ReadFull(chunkData, alphaData) case "VP8X": fmt.Printf("Found VP8X chunk: %d bytes\n", chunkLen) data := make([]byte, 10) io.ReadFull(chunkData, data) } } if !vp8Chunk && !vp8lChunk { return fmt.Errorf("no image data chunk found") } fmt.Printf("WebP file: VP8%s with %s\n", map[bool]string{true: "L"}[vp8lChunk], map[bool]string{true: "alpha", false: "no alpha"}[len(alphaData) > 0]) return nil } ``` -------------------------------- ### Compose 2D Transformations Source: https://github.com/golang/image/blob/master/_autodocs/09-math-float-package.md Demonstrates composing 2D affine transformations (translation and rotation) and applying the combined matrix to a point. ```go // Apply translation then rotation trans := translate(10, 20) rot := rotate(math.Pi / 4) // 45 degrees combined := rot.Mul(trans) // Note: right-to-left order point := f32.Vec2{5, 5} transformed := combined.MulVec2(point) ``` -------------------------------- ### Draw Rectangle using Vector Rasterizer Source: https://github.com/golang/image/blob/master/_autodocs/08-vector-package.md Draws a rectangle on a destination image using the vector package. This example uses floating-point coordinates and the standard Rasterizer. ```go import ( "golang.org/x/image/vector" "image" "image/color" "image/draw" ) func drawRectangle(dst draw.Image, x0, y0, x1, y1 float32, color color.Color) { z := vector.NewRasterizer(dst.Bounds().Dx(), dst.Bounds().Dy()) z.MoveTo(x0, y0) z.LineTo(x1, y0) z.LineTo(x1, y1) z.LineTo(x0, y1) z.Close() z.Rasterize(dst, color) } ``` -------------------------------- ### List All Available Colors Source: https://github.com/golang/image/blob/master/_autodocs/10-colornames-package.md Prints all available named colors from the colornames package to standard output, sorted alphabetically. Requires importing 'fmt', 'sort', and 'golang.org/x/image/colornames'. ```go import ( "fmt" "sort" "golang.org/x/image/colornames" ) func listAllColors() { names := make([]string, 0, len(colornames.Map)) for name := range colornames.Map { names = append(names, name) } sort.Strings(names) for _, name := range names { fmt.Println(name) } } ``` -------------------------------- ### Text Rendering with Drawer Source: https://github.com/golang/image/blob/master/_autodocs/README.md Render text onto an image using a font.Face and a draw.Image. ```go import ( "golang.org/x/image/font" "golang.org/x/image/font/basicfont" "golang.org/x/image/draw" "image" ) func DrawText(img draw.Image, text string, pos image.Point, clr color.Color) { drawer := &font.Drawer{ Dst: img, Src: color.NewAlpha16(uint16(color.NRGBA{R: 0xff, G: 0xff, B: 0xff, A: 0xff}.RGBA())), Face: basicfont.Face7x13, // Example font face Dot: pos, } drawer.DrawString(text) } ``` -------------------------------- ### Batch Process Images (BMP to TIFF) Source: https://github.com/golang/image/blob/master/_autodocs/13-usage-examples.md Provides a function to process all BMP images in an input directory, scale them down by 50%, and save them as TIFF files with Deflate compression in an output directory. This is useful for automated image conversion workflows. Requires 'fmt', 'os', 'path/filepath', 'golang.org/x/image/bmp', 'golang.org/x/image/draw', and 'golang.org/x/image/tiff'. ```go package main import ( "fmt" "os" "path/filepath" "golang.org/x/image/bmp" "golang.org/x/image/draw" "golang.org/x/image/tiff" ) func processImages(inputDir, outputDir string) error { // Create output directory os.MkdirAll(outputDir, 0755) // Find all BMP files files, _ := filepath.Glob(filepath.Join(inputDir, "*.bmp")) for _, inputPath := range files { // Load image file, err := os.Open(inputPath) if err != nil { continue } img, err := bmp.Decode(file) file.Close() if err != nil { continue } // Scale down (50%) bounds := img.Bounds() w, h := bounds.Dx()/2, bounds.Dy()/2 scaled := image.NewRGBA(image.Rect(0, 0, w, h)) draw.ApproxBiLinear.Scale(scaled, scaled.Bounds(), img, bounds, draw.Src, nil) // Save as TIFF with compression baseName := filepath.Base(inputPath) outputPath := filepath.Join(outputDir, baseName[:len(baseName)-4]+".tiff") out, err := os.Create(outputPath) if err != nil { continue } opts := &tiff.Options{Compression: tiff.Deflate} tiff.Encode(out, scaled, opts) out.Close() fmt.Printf("Processed: %s -> %s\n", inputPath, outputPath) } return nil } func main() { processImages("./input", "./output") } ``` -------------------------------- ### Convert Pixel Coordinates to Fixed-Point Source: https://github.com/golang/image/blob/master/_autodocs/03-font-package.md Shows how to convert standard pixel coordinates (integers) into the fixed.Point26_6 format used by the font package for precise positioning. The `<< 6` operation shifts bits to account for the 6 fractional bits. ```go pixelX, pixelY := 10, 20 point := fixed.Point26_6{X: fixed.Int26_6(pixelX << 6), Y: fixed.Int26_6(pixelY << 6)} ``` -------------------------------- ### Metrics Method Source: https://github.com/golang/image/blob/master/_autodocs/03-font-package.md Returns the metrics for this face, including line height, ascent, descent, and x-height. ```go func (f Face) Metrics() Metrics ``` -------------------------------- ### FourCC Type and Construction for RIFF Chunks Source: https://github.com/golang/image/blob/master/_autodocs/12-types-and-configuration.md Defines the FourCC type for identifying RIFF chunks and provides examples of construction and common chunk IDs like 'RIFF', 'WEBP', and 'VP8 '. ```go type FourCC [4]byte // Construction var chunkID riff.FourCC copy(chunkID[:], "VP8 ") // Common values "RIFF" // Root container "WEBP" // WebP form type "VP8 " // VP8 lossy chunk "VP8L" // VP8L lossless chunk "ALPH" // Alpha chunk "AVI " // AVI form "WAVE" // WAV form ``` -------------------------------- ### Registering TIFF Format for Image Decoding Source: https://github.com/golang/image/blob/master/_autodocs/05-tiff-package.md Shows how to import the TIFF package to register it with Go's image format registry, enabling decoding of TIFF files using image.Decode(). ```go import "image" import _ "golang.org/x/image/tiff" func main() { img, format, err := image.Decode(file) // format == "tiff" } ``` -------------------------------- ### TIFF Encode Example with Deflate Compression Source: https://github.com/golang/image/blob/master/_autodocs/05-tiff-package.md Encodes an image to TIFF format with Deflate compression. Supports various image types, converting others to 24-bit RGB. Ensure the output file is created and closed. ```go import ( "os" "image" "image/color" "golang.org/x/image/tiff" ) func main() { // Create image img := image.NewGray(image.Rect(0, 0, 100, 100)) // Encode to file file, err := os.Create("output.tiff") if err != nil { panic(err) } defer file.Close() opts := &tiff.Options{Compression: tiff.Deflate} if err := tiff.Encode(file, img, opts); err != nil { panic(err) } } ``` -------------------------------- ### Create CCITT Group 4 Writer Source: https://github.com/golang/image/blob/master/_autodocs/07-ccitt-package.md Creates a new writer to compress data using CCITT Group 4. Write uncompressed 1-bit scanline data to get compressed output. Ensure scanlines are correctly filled. ```go package main import ( "golang.org/x/image/ccitt" ) func main() { // Create writer for Group4 compression // width=800, height=600 writer := ccitt.NewWriter(ccitt.Group4, true, 800, 600) // Write uncompressed scanlines scanline := make([]byte, 100) // 800 pixels = 100 bytes for y := 0; y < 600; y++ { // Fill scanline with data (1 bit per pixel) copy(scanline, [...]) writer.Write(scanline) } // Get compressed data compressed := writer.Close() } ``` -------------------------------- ### Apply Affine Transformation (Rotation) Source: https://github.com/golang/image/blob/master/_autodocs/13-usage-examples.md Loads an image, defines an affine transformation matrix for a 45-degree rotation around the image center, and applies it using approximate bilinear interpolation. The rotated image is saved as a BMP file. ```go package main import ( "image" "math" "os" "golang.org/x/image/bmp" "golang.org/x/image/draw" "golang.org/x/image/math/f64" ) func main() { // Load image file, _ := os.Open("image.bmp") src, _ := bmp.Decode(file) file.Close() bounds := src.Bounds() w, h := bounds.Dx(), bounds.Dy() // Create transformation: rotate 45 degrees around center cx, cy := float64(w)/2, float64(h)/2 angle := math.Pi / 4 // 45 degrees cos, sin := math.Cos(angle), math.Sin(angle) // Rotation matrix m := f64.Aff3{ cos, -sin, cx - cx*cos + cy*sin, sin, cos, cy - cx*sin - cy*cos, } // Create destination dst := image.NewRGBA(bounds) // Apply transformation draw.ApproxBiLinear.Transform(dst, m, src, bounds, draw.Src, nil) // Save out, _ := os.Create("rotated.bmp") bmp.Encode(out, dst) out.Close() } ``` -------------------------------- ### Convert Int26_6 to pixel coordinates with rounding and flooring Source: https://github.com/golang/image/blob/master/_autodocs/06-math-fixed-package.md Shows how to convert fixed-point values (Int26_6) to integer pixel coordinates using Round(), Floor(), and Ceil() methods. Also demonstrates converting pixels back to Int26_6. ```go // Convert Int26_6 to pixel coordinate (integer) fixed := fixed.I(10) + 32 // 10.5 pixel := fixed.Round() // 11 (rounded) pixel := fixed.Floor() // 10 (floored) pixel := fixed.Ceil() // 11 (ceiled) // Convert pixel to Int26_6 pixel := 10 fixed := fixed.I(pixel) // 10.0 ``` -------------------------------- ### Matrix Column-Major Order Explanation Source: https://github.com/golang/image/blob/master/_autodocs/09-math-float-package.md Illustrates the column-major order convention used for matrices in Go's image math packages, following OpenGL standards. This is crucial for correct matrix manipulation. ```go // m = [col0, col1, col2, col3] for Mat2 (example for Mat4) // or logically: // [m[0]] [m[4]] [m[8]] [m[12]] // [m[1]] [m[5]] [m[9]] [m[13]] // [m[2]] [m[6]] [m[10]] [m[14]] // [m[3]] [m[7]] [m[11]] [m[15]] ``` -------------------------------- ### Convert BMP to TIFF with Deflate Compression Source: https://github.com/golang/image/blob/master/_autodocs/13-usage-examples.md Shows how to decode a BMP image and then encode it as a TIFF file with Deflate compression. This is useful for reducing file size while maintaining image quality. Requires 'os', 'golang.org/x/image/bmp', and 'golang.org/x/image/tiff'. ```go package main import ( "os" "golang.org/x/image/bmp" "golang.org/x/image/tiff" ) func main() { // Decode BMP bmpFile, _ := os.Open("input.bmp") img, _ := bmp.Decode(bmpFile) bmpFile.Close() // Encode as TIFF with compression tiffFile, _ := os.Create("output.tiff") opts := &tiff.Options{Compression: tiff.Deflate} tiff.Encode(tiffFile, img, opts) tiffFile.Close() } ``` -------------------------------- ### FixedPointRasterizer Methods Overview Source: https://github.com/golang/image/blob/master/_autodocs/08-vector-package.md Provides an overview of the methods available for the FixedPointRasterizer, including path manipulation and rasterization. These methods operate on fixed-point coordinates. ```go func (z *FixedPointRasterizer) MoveTo(x, y fixed.Int26_6) ``` ```go func (z *FixedPointRasterizer) LineTo(x, y fixed.Int26_6) ``` ```go func (z *FixedPointRasterizer) QuadTo(bx, by, x, y fixed.Int26_6) ``` ```go func (z *FixedPointRasterizer) CubeTo(bx0, by0, bx1, by1, x, y fixed.Int26_6) ``` ```go func (z *FixedPointRasterizer) Close() ``` ```go func (z *FixedPointRasterizer) Rasterize(dst draw.Image, color color.Color) ``` -------------------------------- ### Register WebP Decoder with Image Package Source: https://github.com/golang/image/blob/master/_autodocs/04-webp-package.md Imports the webp package to register its decoder with Go's standard image package. This allows using image.Decode() to automatically detect and decode WebP files. ```go import "image" import _ "golang.org/x/image/webp" func main() { img, format, err := image.Decode(file) // format == "webp" } ``` -------------------------------- ### Create 2D Scaling Matrix (f32.Aff3) Source: https://github.com/golang/image/blob/master/_autodocs/09-math-float-package.md Provides a function to generate a 2x3 affine matrix for scaling in 2D. ```go func scale(sx, sy float32) f32.Aff3 { return f32.Aff3{sx, 0, 0, 0, sy, 0} } ``` -------------------------------- ### Create FourCC from String Source: https://github.com/golang/image/blob/master/_autodocs/11-riff-package.md Demonstrates how to create a FourCC type from a string literal or by directly assigning characters. ```go import "golang.org/x/image/riff" func main() { var webpType riff.FourCC copy(webpType[:], "WEBP") var vp8Type = riff.FourCC{'V', 'P', '8', ' '} } ``` -------------------------------- ### Typical Graphics Usage Source: https://github.com/golang/image/blob/master/_autodocs/09-math-float-package.md Illustrates a typical graphics usage scenario involving image transformation using the `draw.ApproxBiLinear.Transform` function with an `f64.Aff3` matrix. ```APIDOC ## Typical Graphics Usage ### 2D Transformations ```go import ( "golang.org/x/image/draw" "golang.org/x/image/math/f64" ) func transformImage(dst draw.Image, src image.Image) { // Rotation and scale m := f64.Aff3{2, 0, 50, 0, 2, 75} // 2x scale, translate (50,75) draw.ApproxBiLinear.Transform(dst, m, src, src.Bounds(), draw.Src, nil) } ``` ``` -------------------------------- ### Floating-Point Matrix Multiplication (f64) Source: https://github.com/golang/image/blob/master/_autodocs/README.md Multiply two 64-bit floating-point 3x3 matrices. ```go import "golang.org/x/image/math/f64" func MulMat3f64(a, b f64.Mat3) f64.Mat3 { return a.Mul(b) } ``` -------------------------------- ### Drawer DrawRunes Method Source: https://github.com/golang/image/blob/master/_autodocs/03-font-package.md Renders a slice of runes (Unicode codepoints) using the Drawer's current settings. Useful for pre-processed text. ```go func (d *Drawer) DrawRunes(runes []rune) ``` -------------------------------- ### Image Composition and Scaling Source: https://github.com/golang/image/blob/master/_autodocs/DOCUMENTATION_SUMMARY.txt Provides tools for image composition, scaling, and transformation using various interpolators. ```Go package draw // Copier is an optimized image.Image copier. // The Copy method copies the image src to dst. // The src and dst images must have the same bounds. // The Copy method panics if the bounds are not equal. type Copier interface { Copy(dst Image, src image.Image) } // Scaler scales an image.Image to a new image. // The Scale method scales the image src to the image dst. // The src and dst images must have the same bounds. // The Scale method panics if the bounds are not equal. type Scaler interface { Scale(dst image.Image, src image.Image) } // Transformer transforms an image.Image to a new image. // The Transform method transforms the image src to the image dst. // The src and dst images must have the same bounds. // The Transform method panics if the bounds are not equal. type Transformer interface { Transform(dst image.Image, src image.Image) } ``` -------------------------------- ### Create and Draw a Path with Rasterizer Source: https://github.com/golang/image/blob/master/_autodocs/08-vector-package.md Creates a new rasterizer and defines a rectangular path. This is useful for setting up the drawing surface and defining basic shapes. ```Go package main import ( "golang.org/x/image/vector" ) func main() { // Create rasterizer for 200x200 pixel image z := vector.NewRasterizer(200, 200) // Define path z.MoveTo(50, 50) z.LineTo(150, 50) z.LineTo(150, 150) z.LineTo(50, 150) z.Close() // Rasterize dst := image.NewRGBA(image.Rect(0, 0, 200, 200)) z.Rasterize(dst, color.White) } ``` -------------------------------- ### Create Point26_6 from integer coordinates Source: https://github.com/golang/image/blob/master/_autodocs/06-math-fixed-package.md Creates a Point26_6 from integer x and y coordinates. This is a convenience function for initializing points. ```go func P(x, y int) Point26_6 ``` ```go pt := fixed.P(10, 20) // (10.0, 20.0) in 26.6 format ``` -------------------------------- ### Draw Rectangle Source: https://github.com/golang/image/blob/master/_autodocs/13-usage-examples.md Demonstrates how to draw a filled rectangle on an image using the vector rasterizer. Requires importing 'image', 'image/color', 'os', 'golang.org/x/image/bmp', and 'golang.org/x/image/vector'. ```go package main import ( "image" "image/color" "math" "os" "golang.org/x/image/bmp" "golang.org/x/image/vector" ) func main() { // Create rasterizer z := vector.NewRasterizer(200, 200) dst := image.NewRGBA(image.Rect(0, 0, 200, 200)) // Draw rectangle z.MoveTo(20, 20) z.LineTo(180, 20) z.LineTo(180, 180) z.LineTo(20, 180) z.Close() z.Rasterize(dst, color.White) // Save file, _ := os.Create("rectangle.bmp") bmp.Encode(file, dst) file.Close() } ```