imgdiet

package module
v0.2.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Oct 22, 2024 License: MIT Imports: 9 Imported by: 0

README

imgdiet

Go Documentation Go Report Card Coverage Report builds.sr.ht status

imgdiet is a Go module built for optimizing images. It leverages the power of the libvips library to provide an easy-to-use, lightweight, and idiomatic way to reduce image size without significant loss of quality.

Note: Only PNG, GIF, and JPG images are supported at the moment. Support for more image formats is expected to be added in the future. Patches are welcome.

Prerequisites

You'll need to have Go v1.23 and libvips installed on your system to use imgdiet. If you wish to use the command-line tool as well, you'll also need make and scdoc installed.

Installation

To install imgdiet, run:

go get git.sr.ht/~jamesponddotco/imgdiet-go@latest

You can also install the command-line application by running:

make
sudo make install

Usage

As a Go module

You can use imgdiet in your own Go applications like this:

package main

import (
	"log"
	"os"

	"git.sr.ht/~jamesponddotco/imgdiet-go"
)

func main() {
	// Start libvips with default settings. This is optional, but
	// recommended.
	imgdiet.Start(nil)
	defer imgdiet.Stop()

	// Open an image file as an io.Reader.
	file, err := os.Open("image.jpg")
	if err != nil {
		log.Fatal(err)
	}
	defer file.Close()

	// Open the image for processing.
	img, err := imgdiet.Open(file)
	if err != nil {
		log.Fatal(err)
	}
	defer img.Close()

	// Optimize the image for web use with default settings.
	image, err := img.Optimize(imgdiet.DefaultOptions())
	if err != nil {
		log.Fatal(err)
	}

	// Do something with the byte slice of the optimized image.
}

For more examples and usage details, please check the Go reference documentation.

As a CLI tool
$ imgdiet --help
NAME:
   imgdiet - A CLI tool to optimize and resize images

USAGE:
   imgdiet [global options] [arguments...]

VERSION:
   0.1.0

GLOBAL OPTIONS:
   --quality value, -q value      set the quality of the output image (default: 60)
   --compression value, -c value  set the compression level of the output image (default: 9)
   --interlace, -i                whether to interlace the output image (default: false)
   --strip, -s                    whether to strip metadata from the output image (default: false)
   --optimize-icc-profile, -p     whether to optimize the ICC profile of the output image (default: false)
   --overwrite, -w                whether to overwrite the already existing output image (default: false)
   --help, -h                     show help
   --version, -v                  print the version

See imgdiet(1) after installing for more information.

Contributing

Anyone can help make imgdiet better. Send patches to the mailing list and report bugs on the issue tracker.

You must sign-off your work using git commit --signoff. Follow the Linux kernel developer's certificate of origin for more details.

All contributions are made under the MIT license.

Resources

The following resources are available:


Released under the MIT License.

Documentation

Overview

Package imgdiet offers a simple and fast image processing and compression solution by leveraging C's [libvips] image processing library and its Go binding, [govips].

[libvips]: https://github.com/libvips/libvips [govips]: https://github.com/davidbyttow/govips

Index

Constants

View Source
const (
	ErrOpenImage               xerrors.Error = "failed to open image"
	ErrNilImage                xerrors.Error = "image is nil"
	ErrInvalidResizeDimensions xerrors.Error = "dimensions must be greater than 0"
)
View Source
const (
	ImageTypeJPEG string = "JPEG"
	ImageTypePNG  string = "PNG"
	ImageTypeGIF  string = "GIF"
)

List of image types supported by this package.

View Source
const (
	LogLevelError    = vips.LogLevelError
	LogLevelCritical = vips.LogLevelCritical
	LogLevelWarning  = vips.LogLevelWarning
	LogLevelMessage  = vips.LogLevelMessage
	LogLevelInfo     = vips.LogLevelInfo
	LogLevelDebug    = vips.LogLevelDebug
)

List of libvips logging levels for convenience.

View Source
const ErrUnsupportedImageFormat xerrors.Error = "unsupported image format"

ErrUnsupportedImageFormat is returned when the image format is not supported by this package.

Variables

This section is empty.

Functions

func DefaultLogger

func DefaultLogger(_ string, verbosity vips.LogLevel, message string)

DefaultLogger is a very simple logger the package uses by default. It complies with vips.LoggingHandlerFunction.

func DetectImageSize

func DetectImageSize(image []byte) int64

DetectImageSize takes an image as a byte array input and detects the image size in bytes.

func DetectImageType

func DetectImageType(image []byte) (string, error)

DetectImageType takes an image as a byte array input and detects its type based on its magic bytes. It returns a string representation of the image type and an error if the image type is not supported.

func Start

func Start(cfg *Config)

Start initializes the libvips library with the given configuration.

func Stop

func Stop()

Stop shuts down the libvips library.

Types

type Config

type Config struct {
	// Logger defines the logger to be used by libvips.
	Logger func(domain string, verbosity vips.LogLevel, message string)

	// LogLevel is the level of logging to be used by libvips.
	LogLevel vips.LogLevel

	// Cache defines the size of the libvips cache in bytes.
	Cache int

	// MaxConcurrency defines the maximum number of concurrent operations that
	// libvips can perform.
	MaxConcurrency int

	// ReportLeaks defines whether libvips should report memory leaks.
	ReportLeaks bool
}

Config defines the configuration for the libvips library.

func DefaultConfig

func DefaultConfig() *Config

DefaultConfig returns a set of opinionated and sane defaults for the libvips library.

type Image

type Image struct {
	// contains filtered or unexported fields
}

Image defines an image to be optimized and manages its lifecycle.

func Open

func Open(r io.Reader) (*Image, error)

Open takes an io.Reader as input for reading and returns an Image instance.

func (*Image) Close

func (i *Image) Close()

Close releases the resources associated with the Image.

func (*Image) Height

func (i *Image) Height() int

Height returns the height of the image in pixels.

func (*Image) Optimize

func (i *Image) Optimize(opts *Options) ([]byte, error)

Optimize takes the given Options and optimizes the image accordingly. It returns the optimized image as a byte slice or an error if the optimization fails.

func (*Image) Resize

func (i *Image) Resize(width, height int, opts *Options) ([]byte, error)

Resize takes a set of dimensions and resizes the image to those dimensions. If opts is not nil, the resulting image is optimized according to the given Options.

func (*Image) Saved

func (i *Image) Saved() int64

Saved returns the size of the image after optimization in bytes.

func (*Image) Size

func (i *Image) Size() int64

Size returns the size of the image in bytes.

func (*Image) Width

func (i *Image) Width() int

Width returns the width of the image in pixels.

type Options

type Options struct {
	// Quality defines the quality of the output image. It is a number between 0
	// and 100.
	Quality int

	// Compression defines the compression level of the output image. It is a
	// number between 0 and 9.
	//
	// Only valid for PNG images.
	Compression int

	// Effort defines the level of CPU effort to be used when optimizing the
	// output image. It is a number between 0 and 9.
	//
	// Only valid for GIF images.
	Effort int

	// QuantTable defines the quantization table to be used for the output
	// image. It is a number between 0 and 8.
	//
	// Only valid for JPEG images.
	QuantTable int

	// Bitdepth defines the number of bits per pixel of the output image. It is
	// a number between 1 and 8.
	//
	// Only valid for GIF and PNG images.
	Bitdepth int

	// Dither defines the amount of dithering to be applied during 8bpp (bits
	// per pixel) quantization. It is a floating-point number between 0 and 1.
	//
	// Only valid for GIF and PNG images.
	Dither float64

	// OptimizeCoding defines whether the output image should have its coding
	// optimized.
	//
	// Only valid for JPEG images.
	OptimizeCoding bool

	// Interlaced defines whether the output image should be interlaced.
	Interlaced bool

	// StripMetadata defines whether the output image should have its metadata
	// stripped.
	StripMetadata bool

	// OptimizeICCProfile defines whether the output image should have its ICC
	// profile optimized.
	OptimizeICCProfile bool

	// TrellisQuant defines whether the output image should have its
	// quantization tables optimized using trellis quantization.
	//
	// Only valid for JPEG images.
	TrellisQuant bool

	// OvershootDeringing defines whether the output image should have its
	// quantization tables optimized using overshoot deringing.
	//
	// Only valid for JPEG images.
	OvershootDeringing bool

	// OptimizeScans defines whether the output image should have its scans
	// optimized.
	//
	// Only valid for JPEG images.
	OptimizeScans bool
}

Options represents the parameters used to optimize an image.

func DefaultOptions

func DefaultOptions() *Options

DefaultOptions returns a set of opinionated defaults for optimizing images.

Directories

Path Synopsis
cmd
imgdiet/internal/app
Package app is the main package for the application.
Package app is the main package for the application.
imgdiet/internal/meta
Package meta provides build information and other metadata for the application.
Package meta provides build information and other metadata for the application.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL