Using img in Go

All the functionality of img, and more, is available to use as a library. You can read the package documentation if you just want to dive in. But here are some tips.

Input/Output

img makes heavy use of STDIN and STDOUT for composition of tools. It provides the functions utils.ReadStin and utils.WriteStdout to make this as simple as possible. For example, a simple program that reads an image, runs it through pxl, and greyscales the result.

package main

import (
  "hawx.me/code/img/greyscale"
  "hawx.me/code/img/pixelate"
  "hawx.me/code/img/utils"
)

func main() {
  // Read image and data
  img, data = utils.ReadStdin()

  // Modify the image
  img = pixelate.Pxl(img, utils.Dimension{40,40},
                     pixelate.BOTH, pixelate.FITTED)
  img = greyscale.Red(img)

  // Write image
  utils.WriteStdout(img, data)
}

Here img is an image.Image, while data contains any Exif data read from the image.

If writing an External Tool you must respect the given output flag. This is easily done using utils.GetOutput, use it like so:

package main

import (
  "hawx.me/code/img/utils"
  "flag"
  "os"
)

func main() {
  var (
    long  = flag.Bool("long", false, "")
    short = flag.Bool("short", false, "")
    usage = flag.Bool("usage", false, "")
  )

  // Always call before flags are parsed!
  os.Args = utils.GetOutput(os.Args)
  flag.Parse()

  ...
}

Composition

You will find when browsing the documentation that a lot of functions have a version ending with C that returns a utils.Composable object. These can be used to reduce the number of times the image is looped over.

For instance consider this snippet that creates a greyscale version of the image then boosts contrast.

output = greyscale.Default(input)
return contrast.Sigmoidal(output, 2.0, 0.5)

This works fine, but loops over the image twice. We can merge these calls into one loop using utils.Compose and functions that return utils.Composable objects.

return utils.MapColors(input, utils.Compose(
  greyscale.DefaultC(),
  contrast.SigmoidalC(2.0, 0.5),
))

The code here is more complex, but more efficient.

Adjusters

A lot of img tools on the command line take the options --by and --ratio: these are implemented using utils.Adjuster.

A utils.Adjuster is any function that takes a float64 and returns a float64. Two helper functions are defined for creating them, utils.Adder and utils.Multiplier.

You can use these, or your own, in any function which takes a utils.Adjuster, like, for instance changing the hue of an image.

return channel.Adjust(
  input,
  utils.Adder(1.0/6.0),
  channel.Hue,
)