Skip to content

Colors and positions ​

Colors ​

Methods that take a color take a string, which image.ParseColor reads. It accepts these notations, in any case:

NotationExamples
Hex, with or without #f00, #f005, ff0000, #ff000080
rgb() and rgba()rgb(255, 0, 0), rgba(0, 0, 0, 0.4)
hsl() and hsla()hsl(200, 100%, 50%)
CSS color namessteelblue, white
transparenttransparent

ParseColor returns an image.Color, which has straight, non-premultiplied R, G, B, and A fields and implements color.Color. Hex writes it back as hex without #, with an alpha byte when the color isn't opaque:

go
c, err := image.ParseColor("rgba(255, 45, 32, 0.5)")

c.Hex() // "ff2d2080"

Positions ​

Methods that place an image or an area take an image.Position. A position is an alignment, optionally with an offset. A nil position is image.Center.

Alignments ​

ConstantName
image.Centercenter
image.TopLefttop-left
image.Toptop
image.TopRighttop-right
image.Leftleft
image.Rightright
image.BottomLeftbottom-left
image.Bottombottom
image.BottomRightbottom-right

image.ParseAlignment reads these names from user input. It also accepts underscores, either word order, and middle, so top_left, left-top, and center-top work:

go
alignment, err := image.ParseAlignment(r.PathValue("position"))

Offsets ​

Offset moves an alignment by a number of pixels, away from the edges it aligns to. From a right edge, x moves left. From a bottom edge, y moves up:

go
image.TopLeft.Offset(10, 20)     // 10 pixels from the left, 20 from the top
image.BottomRight.Offset(10, 10) // 10 pixels from the right and the bottom

Formats ​

image.FormatOf returns the image.Format for a format name, file extension, media type, or path:

go
image.FormatOf("webp")           // image.WEBP
image.FormatOf(".jpg")           // image.JPEG
image.FormatOf("image/png")      // image.PNG
image.FormatOf("photos/cat.gif") // image.GIF

A format's Extension and MediaType methods return the values to save and serve it with, such as jpg and image/jpeg.

Released under the MIT License.