imgconv

repository·main·Indexed 41 days ago

https://github.com/sunshineplan/imgconv

A Go package and CLI tool for basic image processing tasks, including resizing, splitting, watermarking, and format conversion. It supports formats such as JPEG, PNG, GIF, TIFF, BMP, WEBP, and PDF, and provides functions like imgconv.Resize, imgconv.Split, and imgconv.Watermark for manipulating images that implement the standard image.Image interface.

Tokens
6.5K
Snippets
31
Records
34
Agent score
99%

What's inside imgconv

  1. Overview of imgconv capabilities

    main

    The imgconv package provides basic image processing functions including resizing, splitting, watermarking, and format conversion.

    All processing functions accept any image type that implements the standard image.Image interface. Supported formats include:

    • jpg (jpeg)
    • png
    • gif
    • tif (tiff)
    • bmp
    • webp
    • pdf
  2. Use the imgconv CLI for image conversion

    main

    The imgconv CLI tool allows for batch or single image conversion, resizing, watermarking, and format changes. It supports various formats including jpg, jpeg, png, gif, tif, tiff, bmp, pdf, and webp.

    Common Tasks

    Convert a directory of images to a specific format:

    imgconv --src ./input_folder --dst ./output_folder --format png

    Resize images by width and height (preserving aspect ratio if one is 0):

    imgconv --src photo.jpg --dst output.png --width 800

    Resize images by percentage:

    imgconv --src photo.jpg --dst output.png --percent 50

    Add a watermark with custom opacity and offset:

    imgconv --src photo.jpg --dst output.png --watermark ./logo.png --opacity 150 -x 10 -y 10

    Convert to grayscale and use a white background for transparency:

    imgconv --src photo.png --dst output.jpg --gray --white-background
    # Example: Convert all images in 'photos' to webp with 80% quality
    imgconv --src photos --dst converted_photos --format webp --quality 80
  3. Complete imgconv usage example

    main

    This example demonstrates a full workflow: opening an image, resizing it, adding a random watermark, writing it as a TIFF, writing it as a WEBP with compression, and splitting it horizontally.

    package main
    
    import (
    	"io"
    	"log"
    
    	"github.com/HugoSmits86/nativewebp"
    	"github.com/sunshineplan/imgconv"
    )
    
    func main() {
    	// Open a test image.
    	src, err := imgconv.Open("testdata/video-001.png")
    	if err != nil {
    		log.Fatalf("failed to open image: %v", err)
    	}
    
    	// Resize the image to width = 200px preserving the aspect ratio.
    	mark := imgconv.Resize(src, &imgconv.ResizeOption{Width: 200})
    
    	// Add random watermark set opacity = 128.
    	dst := imgconv.Watermark(src, &imgconv.WatermarkOption{Mark: mark, Opacity: 128, Random: true})
    
    	// Write the resulting image as TIFF.
    	if err := imgconv.Write(io.Discard, dst, &imgconv.FormatOption{Format: imgconv.TIFF}); err != nil {
    		log.Fatalf("failed to write image: %v", err)
    	}
    
    	// Write the resulting image as WEBP with an explicit compression level.
    	if err := imgconv.Write(io.Discard, dst, &imgconv.FormatOption{
    		Format: imgconv.WEBP,
    		EncodeOption: []imgconv.EncodeOption{
    			imgconv.WEBPCompressionLevel(nativewebp.DefaultCompression),
    		},
    	}); err != nil {
    		log.Fatalf("failed to write webp image: %v", err)
    	}
    
    	// Split the image into 3 parts horizontally.
    	imgs, err := imgconv.Split(src, 3, imgconv.SplitHorizontalMode)
    	if err != nil {
    		log.Fatalf("failed to split image: %v", err)
    	}
    }
  4. Add watermarks with imgconv.Watermark

    main

    Use imgconv.Watermark to overlay a watermark image onto a source image. Configuration is handled via *imgconv.WatermarkOption.

    Key options:

    • Mark: The image to use as a watermark.
    • Opacity: The transparency level (e.g., 128).
    • Random: If true, the watermark is placed at a random position.
    • Offset: If Random is false, use image.Pt(x, y) to set a fixed position.
    // srcImage add a watermark at randomly position.
    dstImage := imgconv.Watermark(srcImage, &WatermarkOption{Mark: markImage, Opacity: 128, Random: true})
    
    // srcImage add a watermark at fixed position with offset.
    dstImage := imgconv.Watermark(srcImage, &WatermarkOption{Mark: markImage, Opacity: 128, Offset: image.Pt(5, 5)})
  5. Resize images with imgconv.Resize

    main

    Use imgconv.Resize to change the dimensions of an image. You must provide an *imgconv.ResizeOption struct. You can specify absolute dimensions (Width, Height) or a Percent value. If only one dimension is provided, the aspect ratio is preserved.

    // Resize srcImage to size = 128x128px.
    dstImage128 := imgconv.Resize(srcImage, &imgconv.ResizeOption{Width: 128, Height: 128})
    
    // Resize srcImage to width = 800px preserving the aspect ratio.
    dstImage800 := imgconv.Resize(srcImage, &imgconv.ResizeOption{Width: 800})
    
    // Resize srcImage to 50% size preserving the aspect ratio.
    dstImagePercent50 := imgconv.Resize(srcImage, &imgconv.ResizeOption{Percent: 50})
  6. Split images with imgconv.Split

    main

    Use imgconv.Split to divide an image into multiple parts. You specify the number of parts and the split mode using either imgconv.SplitHorizontalMode or imgconv.SplitVerticalMode.

    // Split srcImage into 3 parts horizontally.
    imgs, err := imgconv.Split(srcImage, 3, imgconv.SplitHorizontalMode)
    
    // Split srcImage into 3 parts vertically.
    imgs, err := imgconv.Split(srcImage, 3, imgconv.SplitVerticalMode)
  7. Convert image formats with imgconv.Write

    main

    Use imgconv.Write to save an image to an io.Writer in a specific format. You must provide an *imgconv.FormatOption specifying the target format (e.g., imgconv.JPEG, imgconv.TIFF, imgconv.WEBP).

    For formats like WEBP, you can also provide EncodeOption slices to control specific encoding parameters like compression levels.

    // Convert srcImage to dst with jpg format.
    imgconv.Write(dstWriter, srcImage, &imgconv.FormatOption{Format: imgconv.JPEG})
    
    // Example with WEBP compression
    imgconv.Write(io.Discard, dst, &imgconv.FormatOption{
    	Format: imgconv.WEBP,
    	EncodeOption: []imgconv.EncodeOption{
    		imgconv.WEBPCompressionLevel(nativewebp.DefaultCompression),
    	},
    })
  8. Customize image encoding with EncodeOption

    main

    The EncodeOption pattern allows fine-grained control over the encoding process for different formats. Use these functions to build your EncodeOption slice:

    FunctionDescription
    Quality(int)Sets JPEG or PDF quality (1-100).
    GIFNumColors(int)Sets max colors for GIF (1-256). Default is 256.
    GIFQuantizer(draw.Quantizer)Sets the quantizer for GIF palette production.
    GIFDrawer(draw.Drawer)Sets the drawer for GIF color conversion.
    PNGCompressionLevel(png.CompressionLevel)Sets PNG compression level.
    TIFFCompressionType(TIFFCompression)Sets TIFF compression (e.g., TIFFDeflate).
    WEBPUseExtendedFormat(bool)Enables/disables WEBP extended format.
    WEBPCompressionLevel(nativewebp.CompressionLevel)Sets WEBP compression level.
    BackgroundColor(color.Color)Sets the background color for images with transparency.
  9. Configure image operations with Options

    main

    The Options struct is the primary way to configure image processing tasks such as watermarking, resizing, grayscale conversion, and format encoding. You can initialize a default configuration using NewOptions() and then use a fluent API to chain settings.

    Available configuration methods:

    • SetWatermark(mark image.Image, opacity uint): Adds a watermark image. If opacity is 0, it defaults to 128.
    • SetResize(width, height int, percent float64): Configures image resizing dimensions and percentage.
    • SetFormat(f Format, options ...EncodeOption): Sets the output image format and any format-specific encoding options.
    • SetGray(gray bool): Enables or disables grayscale conversion.
    import (
    	"image"
    	"os"
    	"imgconv"
    )
    
    // Example: Create options for a resized, grayscale JPEG with a watermark
    func main() {
    	watermark, _ := loadWatermarkImage()
    	file, _ := os.Create("output.jpg")
    	defer file.Close()
    
    	baseImage, _ := loadBaseImage()
    
    	err := imgconv.NewOptions().
    		SetGray(true).
    		SetResize(800, 600, 1.0).
    		SetWatermark(watermark, 200).
    		SetFormat(imgconv.JPEG).
    		Convert(file, baseImage)
    
    	if err != nil {
    		panic(err)
    	}
    }
  10. Encode an image with FormatOption

    main

    To encode an image to a specific format with custom settings, use the FormatOption struct and its Encode method. FormatOption allows you to specify the target Format and a slice of EncodeOption functions to customize the output.

    Encode(w io.Writer, img image.Image) error writes the image to the provided writer.

    option := imgconv.FormatOption{
    	Format: imgconv.JPEG,
    	EncodeOption: []imgconv.EncodeOption{
    		imgconv.Quality(90),
    	},
    }
    
    err := option.Encode(writer, myImage)