ilibgo

package module
v1.0.0 Latest Latest
Warning

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

Go to latest
Published: Jun 19, 2026 License: LGPL-2.1 Imports: 24 Imported by: ? modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

ilibgo — Image Library for Go

Go Reference Go Report Card CI

ilibgo is a pure-Go library for reading, creating, manipulating, and saving images, with a focus on simple drawing primitives and text rendering. It can read any format the standard image package supports and draw text with both embedded X11 BDF bitmap fonts and scalable, anti-aliased TrueType/OpenType fonts.

anti-aliased TrueType text

These are produced by the bundled example tools.

bar chart
chartQR code
qrgenCAPTCHA
captchasparkline
sparklinewatermarked image
watermarkfont specimen sheet
fontsheet

Features

  • Read any format registered with the standard image package; write PNG, JPEG, GIF, BMP, TIFF, and PPM.
  • Drawing primitives: points, lines, rectangles, arcs, circles, ellipses, polygons, flood fill, and (scaled) image copy.
  • Method-style API on *Image (e.g. img.FillRectangle(gc, ...)); *Image implements the standard image.Image and draw.Image interfaces, so it drops into image/draw, the stdlib encoders, and golang.org/x/image scalers.
  • Text: embedded X11 BDF bitmap fonts (with arbitrary-angle rotation and etched/shadowed styles) plus scalable, anti-aliased TrueType/OpenType.
  • No required third-party dependencies beyond golang.org/x/image.

Install

go get github.com/craigk5n/ilibgo

Quick start

package main

import (
	"os"

	"github.com/craigk5n/ilibgo"
	font "github.com/craigk5n/ilibgo/fonts/adobe_100dpi"
)

func main() {
	white, _ := ilibgo.AllocNamedColor("white")
	img := ilibgo.CreateImageWithBackground(240, 80, white)

	gc := ilibgo.CreateGraphicsContext()
	blue, _ := ilibgo.AllocNamedColor("steelblue")
	ilibgo.SetForeground(&gc, blue)
	img.FillRectangle(gc, 10, 10, 220, 60)

	// Draw text with a bundled bitmap font...
	f, _ := ilibgo.LoadFontFromData("helvB18", font.Font_helvB18())
	ilibgo.SetFont(&gc, f)
	white2, _ := ilibgo.AllocNamedColor("white")
	ilibgo.SetForeground(&gc, white2)
	img.DrawString(gc, 24, 50, "Hello, ilibgo!")

	// ...or with a scalable TrueType font:
	// tt, _ := ilibgo.LoadTrueTypeFromFile("Inter.ttf", "inter", 24, 72)
	// ilibgo.SetFont(&gc, tt)

	out, _ := os.Create("hello.png")
	defer out.Close()
	ilibgo.WriteImageFile(out, img, ilibgo.FormatPNG)
}

The drawing operations are methods on *Image. A GraphicsContext (passed by value) carries the foreground/background color, font, and line/text style. The older free-function forms (ilibgo.FillRectangle(img, gc, ...)) still work but are deprecated in favor of the methods.

Fonts

Bitmap (BDF)

The bundled fonts are stored as .bdf files under fonts/ and compiled into the binary with go:embed. Each foundry is its own package exposing Font_<name>() []string accessors, which you pass to LoadFontFromData. You can also load any .bdf at run time with LoadFontFromFile (or from bytes with LoadFontFromBytes).

More BDF fonts are available from the X.Org font project, and you can edit or create them with FontForge. The bdftogo tool converts a .bdf into Go []string source if you prefer that to embedding the file.

Scalable (TrueType / OpenType)
f, _ := ilibgo.LoadTrueTypeFromFile("Inter.ttf", "inter", 32, 72) // path, name, points, dpi
ilibgo.SetFont(&gc, f)
img.DrawString(gc, x, y, "Smooth, anti-aliased text")

TrueType fonts render anti-aliased and support the etched/shadowed text styles. Arbitrary-angle rotation (DrawStringRotatedAngle) is currently supported only for BDF fonts.

Bundled font license

Some Adobe/X.Org BDF fonts are bundled. Per their COPYING notice:

Copyright 1984-1989, 1994 Adobe Systems Incorporated. Copyright 1988, 1994 Digital Equipment Corporation.

Permission to use, copy, modify, distribute and sell this software and its documentation for any purpose and without fee is hereby granted, provided that the above copyright notices appear in all copies ... Adobe Systems and Digital Equipment Corporation make no representations about the suitability of this software for any purpose. It is provided "as is" without express or implied warranty.

Tools and examples

Each is a package main under its own directory; run with go run ./<dir>.

Tool Description
sample Demonstrates the drawing and text API
truetype Render text with a scalable TrueType/OpenType font
chart Bar-chart generator from label=value data
sparkline Tiny inline trend graph from a number list
qrgen Render a QR code (see the qr package)
barcode Render a Code 39 barcode
captcha Distorted-text CAPTCHA generator
watermark Overlay a semi-transparent text watermark
mandelbrot Render the Mandelbrot set (per-pixel coloring)
fontsheet Specimen catalog of the bundled fonts
montage Compose images into a labeled grid
displayfont Render a BDF font's glyphs to a sheet
bdfinfo Print a BDF font's metadata
thumbnails Build a thumbnail index of images
iconvert Convert an image between formats
iresize Resize an image with a selectable filter
webreport Graph Apache access-log activity
bdftogo Convert a .bdf font to Go source

The qr sub-package is a reusable, dependency-free QR Code encoder.

Building and testing

go build ./...
go test ./...                 # unit tests
go test -race -cover ./...    # with the race detector and coverage

CI runs formatting, go vet, the race-enabled tests, and a coverage gate on every push and pull request.

History

This library was ported to Go from the original C version; the API stays close to the C original (which was modeled after the X11 graphics functions), with the leading I dropped from most names. See the ChangeLog for release history.

License

Copyright (C) 2001-2022 Craig Knudsen, craig@k5n.us.

Released under the GNU Lesser General Public License v2.1 — see LICENSE. Bundled BDF fonts carry their own permissive notices (see above).

Documentation

Overview

Image Library for Go

Ilib is a library (and some tools and examples) written in Go that can read, create, manipulate and save images. It is capable of using X11 BDF fonts for drawing text. That means you get lots of fonts to use. You can even create your own if you know how to create an X11 BDF font. It should be able to read any image file that the base Go image package supports. Copyright (C) 2001-2022 Craig Knudsen, craig@k5n.us http://github.com/craigk5n/ilibgo

Index

Examples

Constants

View Source
const (
	DefaultFormatString = "ppm"
	IlibVersion         = "2.0"
	IlibVersionDate     = "11 Aug 2022"

	FormatGIF       ImageFormat = 0
	FormatPPM       ImageFormat = 1
	FormatPGM       ImageFormat = 2
	FormatPBM       ImageFormat = 3
	FormatXPM       ImageFormat = 4
	FormatXBM       ImageFormat = 5
	FormatPNG       ImageFormat = 6
	FormatJPEG      ImageFormat = 7
	FormatTIFF      ImageFormat = 8
	FormatBMP       ImageFormat = 9
	NumberOfFormats uint        = 10
)
View Source
const BlackPixel int = 0

Default color values

View Source
const WhitePixel int = 1

Variables

This section is empty.

Functions

func CopyImage deprecated

func CopyImage(source *Image, dest *Image, gc GraphicsContext, srcX int, srcY int, width int, height int,
	destX int, destY int) error

Deprecated: use (*Image).CopyImage on the destination image.

func CopyImageScaled deprecated

func CopyImageScaled(source *Image, dest *Image,
	srcX int, srcY int, srcWidth int, srcHeight int,
	destX int, destY int, destWidth int, destHeight int) error

Deprecated: use (*Image).CopyImageScaled on the destination image.

func DrawArc deprecated

func DrawArc(img *Image, gc GraphicsContext, x int, y int, r1 int, r2 int, a1 float64, a2 float64) error

Deprecated: use (*Image).DrawArc.

func DrawCircle deprecated

func DrawCircle(img *Image, gc GraphicsContext, x int, y int, r int) error

Deprecated: use (*Image).DrawCircle.

func DrawEllipse deprecated

func DrawEllipse(img *Image, gc GraphicsContext, x int, y int, r1 int, r2 int) error

Deprecated: use (*Image).DrawEllipse.

func DrawEnclosedArc deprecated

func DrawEnclosedArc(img *Image, gc GraphicsContext, x int, y int, r1 int, r2 int, a1 float64, a2 float64) error

Deprecated: use (*Image).DrawEnclosedArc.

func DrawLine deprecated

func DrawLine(img *Image, gc GraphicsContext, x1 int, y1 int, x2 int, y2 int) error

Deprecated: use (*Image).DrawLine.

func DrawPoint deprecated

func DrawPoint(img *Image, gc GraphicsContext, x int, y int) error

Deprecated: use (*Image).DrawPoint.

func DrawPolygon deprecated

func DrawPolygon(img *Image, gc GraphicsContext, points []Point) error

Deprecated: use (*Image).DrawPolygon.

func DrawRectangle deprecated

func DrawRectangle(img *Image, gc GraphicsContext, x int, y int, width int, height int) error

Deprecated: use (*Image).DrawRectangle.

func DrawString deprecated

func DrawString(img *Image, gc GraphicsContext, x int, y int, text string)

Deprecated: use (*Image).DrawString.

func DrawStringRotated deprecated

func DrawStringRotated(img *Image, gc GraphicsContext, x int, y int, text string, direction TextDirection)

Deprecated: use (*Image).DrawStringRotated.

func DrawStringRotatedAngle deprecated

func DrawStringRotatedAngle(img *Image, gc GraphicsContext, x int, y int, text string, angle float64)

Deprecated: use (*Image).DrawStringRotatedAngle.

func Encode

func Encode(w io.Writer, img *Image, format ImageFormat) error

Encode writes img to w in the given format. It is the streaming core of the package's output path: w may be any io.Writer (a file, bytes.Buffer, HTTP response, gzip stream, etc.). The caller owns w and is responsible for closing it.

Example

Encode an image to any io.Writer. A PNG begins with an 8-byte signature.

package main

import (
	"bytes"
	"fmt"

	"github.com/craigk5n/ilibgo"
)

func main() {
	white, _ := ilibgo.AllocNamedColor("white")
	img := ilibgo.CreateImageWithBackground(16, 16, white)

	var buf bytes.Buffer
	if err := ilibgo.Encode(&buf, img, ilibgo.FormatPNG); err != nil {
		panic(err)
	}
	fmt.Printf("%x\n", buf.Bytes()[:8])
}
Output:
89504e470d0a1a0a

func FillArc deprecated

func FillArc(img *Image, gc GraphicsContext, x int, y int, r1 int, r2 int, a1 float64, a2 float64) error

Deprecated: use (*Image).FillArc.

func FillCircle deprecated

func FillCircle(img *Image, gc GraphicsContext, x int, y int, r int) error

Deprecated: use (*Image).FillCircle.

func FillPolygon deprecated

func FillPolygon(img *Image, gc GraphicsContext, points []Point) error

Deprecated: use (*Image).FillPolygon.

func FillRectangle deprecated

func FillRectangle(img *Image, gc GraphicsContext, x int, y int, width int, height int) error

Deprecated: use (*Image).FillRectangle.

func FloodFill deprecated

func FloodFill(img *Image, gc GraphicsContext, x int, y int) error

Deprecated: use (*Image).FloodFill.

func GetFontSize

func GetFontSize(font *Font) (height int, err error)

func IDrawArc deprecated

func IDrawArc(img *Image, gc GraphicsContext, x int, y int, r1 int, r2 int, a1 float64, a2 float64) error

Deprecated: use (*Image).DrawArc.

func IDrawCircle deprecated

func IDrawCircle(img *Image, gc GraphicsContext, x int, y int, r int) error

Deprecated: use (*Image).DrawCircle.

func IDrawEllipse deprecated

func IDrawEllipse(img *Image, gc GraphicsContext, x int, y int, r1 int, r2 int) error

Deprecated: use (*Image).DrawEllipse.

func IDrawEnclosedArc deprecated

func IDrawEnclosedArc(img *Image, gc GraphicsContext, x int, y int, r1 int, r2 int, a1 float64, a2 float64) error

Deprecated: use (*Image).DrawEnclosedArc.

func IFillArc deprecated

func IFillArc(img *Image, gc GraphicsContext, x int, y int, r1 int, r2 int, a1 float64, a2 float64) error

Deprecated: use (*Image).FillArc.

func IFillCircle deprecated

func IFillCircle(img *Image, gc GraphicsContext, x int, y int, r int) error

Deprecated: use (*Image).FillCircle.

func ImageHeight

func ImageHeight(img *Image) int

func ImageWidth

func ImageWidth(img *Image) int

func IsSupportedFormat

func IsSupportedFormat(stringFormat string) bool

Check to see if the specified image format (as represented as the file suffix like "png") is supported. Some image formats

func SaveImageFile

func SaveImageFile(path string, img *Image, format ImageFormat) error

SaveImageFile encodes img to the file at path, creating or truncating it. It is a convenience wrapper that opens the file, encodes, and closes it, joining any encode and close errors so a failed flush is not lost.

func SetBackground

func SetBackground(gc *GraphicsContext, backgroundColor Color)

func SetFont

func SetFont(gc *GraphicsContext, font *Font)

func SetForeground

func SetForeground(gc *GraphicsContext, foregroundColor Color)

func SetLineStyle

func SetLineStyle(gc *GraphicsContext, lineStyle LineStyle)

func SetLineWidth

func SetLineWidth(gc *GraphicsContext, lineWidth int)

func SetPoint deprecated

func SetPoint(img *Image, gc GraphicsContext, x int, y int) error

Deprecated: use (*Image).SetPoint.

func SetTextStyle

func SetTextStyle(gc *GraphicsContext, textStyle TextStyle)

func TextDimensions

func TextDimensions(gc GraphicsContext, font *Font, text string) (width int, height int, err error)

func TextHeight

func TextHeight(gc GraphicsContext, font *Font, text string) (height int, err error)

Get the height (in pixels) of the specified text using the font currently set in the graphics context.

func TextWidth

func TextWidth(gc GraphicsContext, font *Font, text string) (width int, err error)

Get the width (in pixels) of the specified text using the font currently set in the graphics context.

func WriteImageFile

func WriteImageFile(f io.Writer, img *Image, format ImageFormat) error

WriteImageFile writes an image to an already-open file (or any io.Writer). The writer is left open for the caller to close. It is a thin wrapper over Encode.

Types

type BdfChar

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

func FontBDFGetChar

func FontBDFGetChar(font *BdfFont, ch string) (char *BdfChar)

Get the BdfChar value for the specified letter. Note: Only tested on ASCII with English so far.

func FontBDFGetRune

func FontBDFGetRune(font *BdfFont, ch rune) (char *BdfChar)

Get the BdfChar value for the specified letter. Note: Only tested on ASCII with English so far.

type BdfFont

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

type Color

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

func AllocColor

func AllocColor(red, green, blue uint8) (Color, error)

Allocate a color (with no alpha) from RGB values 0-255.

func AllocNamedColor

func AllocNamedColor(name string) (Color, error)

Allocate a color (with no alpha) by its name (e.g. "red", "blue", etc)

Example

Look up a color by its X11 name.

package main

import (
	"fmt"

	"github.com/craigk5n/ilibgo"
)

func main() {
	red, err := ilibgo.AllocNamedColor("red")
	if err != nil {
		panic(err)
	}
	r, g, b, a := red.RGBA()
	fmt.Println(r>>8, g>>8, b>>8, a>>8)
}
Output:
255 0 0 255

func GetPoint deprecated

func GetPoint(img *Image, x int, y int) Color

Deprecated: use (*Image).GetPoint.

func NewColor

func NewColor(red uint8, green uint8, blue uint8, alpha uint8) Color

NewColor constructs a Color from 8-bit red, green, blue and alpha values. Use this when you need control over alpha; AllocColor is the opaque shortcut.

func (Color) RGBA

func (c Color) RGBA() (r, g, b, a uint32)

RGBA returns the alpha-premultiplied red, green, blue and alpha values for the color, each in the range [0, 0xffff]. This makes Color satisfy the standard image/color.Color interface so callers can read a Color back and use it with the image and image/draw packages.

type FillStyle

type FillStyle int

Fill styles for use with FillStyle

const (
	FillSolid          FillStyle = 1 // default
	FillTiled          FillStyle = 2 // Not yet implemented
	FillStippled       FillStyle = 3 // Not yet implemented
	FillOpaqueStippled FillStyle = 4 // Not yet implemented
)

type Font

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

Font is a loaded font. It is backed either by a bitmap BDF font (font != nil) or by a scalable TrueType/OpenType face at a fixed size (face != nil).

func LoadFontFromBytes

func LoadFontFromBytes(name string, data []byte) (*Font, error)

LoadFontFromBytes parses a BDF font from its raw bytes, for example a file embedded with go:embed. It splits the data into lines (handling both "\n" and "\r\n") and delegates to LoadFontFromData.

func LoadFontFromData

func LoadFontFromData(name string, lines []string) (*Font, error)

Parse the array of string lines that represent the BDF font. Example usage: LoadFontFromData("timR12", font_timR12)

func LoadFontFromFile

func LoadFontFromFile(path string, name string) (*Font, error)

Parse a BFF font file. Example usage: LoadFontFromFile("timR12.bdf", "timR12")

func LoadTrueTypeFromBytes

func LoadTrueTypeFromBytes(data []byte, name string, points float64, dpi float64) (*Font, error)

LoadTrueTypeFromBytes parses a TrueType or OpenType font from raw bytes and builds a Font rasterized at the given point size and resolution. Because TrueType is scalable, the size is baked into the returned Font; load again at a different size to change it. A dpi of 0 defaults to 72 (so points == pixels).

Unlike BDF fonts, a TrueType font renders anti-aliased. It supports the etched/shadowed text styles and arbitrary-angle rotation via DrawStringRotatedAngle (the glyphs are rasterized horizontally and then affine-transformed).

func LoadTrueTypeFromFile

func LoadTrueTypeFromFile(path string, name string, points float64, dpi float64) (*Font, error)

LoadTrueTypeFromFile loads a TrueType/OpenType font file (see LoadTrueTypeFromBytes).

func (*Font) Ascent

func (f *Font) Ascent() int

Ascent returns the font ascent in pixels. For TrueType fonts this is derived from the rasterized face height.

func (*Font) Descent

func (f *Font) Descent() int

Descent returns the BDF font descent in pixels. Zero for TrueType fonts.

func (*Font) FaceName

func (f *Font) FaceName() string

FaceName returns the BDF FACE_NAME. Empty for TrueType fonts.

func (*Font) Family

func (f *Font) Family() string

Family returns the BDF FAMILY_NAME (e.g. "Helvetica"). Empty for TrueType.

func (*Font) Foundry

func (f *Font) Foundry() string

Foundry returns the BDF FOUNDRY (e.g. "Adobe"). Empty for TrueType fonts.

func (*Font) GlyphCount

func (f *Font) GlyphCount() int

GlyphCount returns the number of defined glyphs (ASCII/Latin-1 plus any extra named glyphs). Zero for TrueType fonts.

func (*Font) IsTrueType

func (f *Font) IsTrueType() bool

IsTrueType reports whether the font is backed by a scalable TrueType/OpenType face rather than a bitmap BDF font.

func (*Font) Name

func (f *Font) Name() string

Name returns the name the font was loaded with.

func (*Font) PixelSize

func (f *Font) PixelSize() int

PixelSize returns the BDF PIXEL_SIZE. Zero for TrueType fonts.

func (*Font) Proportional

func (f *Font) Proportional() bool

Proportional reports whether the BDF font uses proportional (vs fixed) spacing. False for TrueType fonts.

func (*Font) Slant

func (f *Font) Slant() string

Slant returns the BDF SLANT code ("R" roman, "I" italic, "O" oblique). Empty for TrueType fonts.

func (*Font) Weight

func (f *Font) Weight() string

Weight returns the BDF WEIGHT_NAME (e.g. "Medium", "Bold"). Empty for TrueType fonts.

type GraphicsContext

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

func CreateGraphicsContext

func CreateGraphicsContext() GraphicsContext

Create a graphics context

type Image

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

func CreateImage

func CreateImage(width int, height int) *Image

func CreateImageWithBackground

func CreateImageWithBackground(width int, height int, background Color) *Image
Example

Create a blank canvas with a solid background color.

package main

import (
	"fmt"

	"github.com/craigk5n/ilibgo"
)

func main() {
	white, _ := ilibgo.AllocNamedColor("white")
	img := ilibgo.CreateImageWithBackground(320, 240, white)
	fmt.Printf("%dx%d\n", ilibgo.ImageWidth(img), ilibgo.ImageHeight(img))
}
Output:
320x240

func Decode

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

Decode reads an image from r (any io.Reader) and returns it as an *Image. The format is detected automatically from the stream contents via the registered image decoders. The caller owns r.

func LoadImageFile

func LoadImageFile(path string) (*Image, error)

LoadImageFile opens the image file at path, decodes it, and closes the file.

func ReadImageFile

func ReadImageFile(f io.Reader) (*Image, error)

ReadImageFile creates an image from an already-open file (or any io.Reader). The reader is left open for the caller to close. It is a thin wrapper over Decode.

func (*Image) At

func (img *Image) At(x int, y int) color.Color

At returns the color of the pixel at (x, y).

func (*Image) Bounds

func (img *Image) Bounds() image.Rectangle

Bounds returns the domain over which the image's pixels are defined.

func (*Image) ColorModel

func (img *Image) ColorModel() color.Model

ColorModel returns the image's color model (color.RGBAModel).

func (*Image) CopyImage

func (dest *Image) CopyImage(source *Image, gc GraphicsContext, srcX int, srcY int, width int, height int,
	destX int, destY int) error

CopyImage copies a rectangular region of source onto this (destination) image. The gc parameter is retained for API compatibility but is unused; the copy is a straight pixel transfer clipped to both images' bounds.

func (*Image) CopyImageScaled

func (dest *Image) CopyImageScaled(source *Image,
	srcX int, srcY int, srcWidth int, srcHeight int,
	destX int, destY int, destWidth int, destHeight int) error

CopyImageScaled scales a region of source onto this (destination) image using nearest-neighbor sampling. For smoother results, use CopyImageScaledQuality.

func (*Image) CopyImageScaledQuality

func (dest *Image) CopyImageScaledQuality(source *Image,
	srcX int, srcY int, srcWidth int, srcHeight int,
	destX int, destY int, destWidth int, destHeight int,
	quality ScaleQuality) error

CopyImageScaledQuality scales a region of source onto this (destination) image using the chosen resampling filter, delegating to golang.org/x/image/draw. Unlike CopyImageScaled (nearest-neighbor only), it can produce smooth, anti-aliased results. The destination region is overwritten (no alpha blending).

func (*Image) DrawArc

func (image *Image) DrawArc(gc GraphicsContext, x int, y int, r1 int, r2 int, a1 float64, a2 float64) error

Draw an arc. Both arc1 and arc2 are in degrees from 0 to 360.

func (*Image) DrawCircle

func (image *Image) DrawCircle(gc GraphicsContext, x int, y int, r int) error

DrawCircle draws the outline of a circle.

func (*Image) DrawEllipse

func (image *Image) DrawEllipse(gc GraphicsContext, x int, y int, r1 int, r2 int) error

DrawEllipse draws the outline of an ellipse with radii r1 and r2.

func (*Image) DrawEnclosedArc

func (image *Image) DrawEnclosedArc(gc GraphicsContext, x int, y int, r1 int, r2 int, a1 float64, a2 float64) error

Draw an arc and connect it to the center point.

func (*Image) DrawLine

func (image *Image) DrawLine(gc GraphicsContext, x1 int, y1 int, x2 int, y2 int) error

func (*Image) DrawPoint

func (image *Image) DrawPoint(gc GraphicsContext, x int, y int) error

DrawPoint sets the point at (x, y) using the graphics context's foreground color. (Alias for SetPoint.)

func (*Image) DrawPolygon

func (image *Image) DrawPolygon(gc GraphicsContext, points []Point) error

func (*Image) DrawRectangle

func (image *Image) DrawRectangle(gc GraphicsContext, x int, y int, width int, height int) error

DrawRectangle draws the outline of a rectangle.

func (*Image) DrawString

func (image *Image) DrawString(gc GraphicsContext, x int, y int, text string)
Example

Render text with a bundled X11 BDF font. The font is loaded from the embedded accessor, set on the GraphicsContext, then drawn.

package main

import (
	"fmt"

	"github.com/craigk5n/ilibgo"
	font "github.com/craigk5n/ilibgo/fonts/adobe_100dpi"
)

func main() {
	white, _ := ilibgo.AllocNamedColor("white")
	black, _ := ilibgo.AllocNamedColor("black")
	img := ilibgo.CreateImageWithBackground(200, 40, white)

	f, err := ilibgo.LoadFontFromData("helvB12", font.Font_helvB12())
	if err != nil {
		panic(err)
	}
	gc := ilibgo.CreateGraphicsContext()
	ilibgo.SetForeground(&gc, black)
	ilibgo.SetFont(&gc, f)
	img.DrawString(gc, 10, 25, "Hello, ilibgo")

	w, _ := ilibgo.TextWidth(gc, f, "Hello, ilibgo")
	fmt.Println(w > 0)
}
Output:
true

func (*Image) DrawStringRotated

func (image *Image) DrawStringRotated(gc GraphicsContext, x int, y int, text string, direction TextDirection)

func (*Image) DrawStringRotatedAngle

func (image *Image) DrawStringRotatedAngle(gc GraphicsContext, x int, y int, text string, angle float64)

func (*Image) FillArc

func (image *Image) FillArc(gc GraphicsContext, x int, y int, r1 int, r2 int, a1 float64, a2 float64) error

Fill an arc

func (*Image) FillCircle

func (image *Image) FillCircle(gc GraphicsContext, x int, y int, r int) error

FillCircle draws a filled circle.

func (*Image) FillPolygon

func (image *Image) FillPolygon(gc GraphicsContext, points []Point) error

Fill a polygonn

func (*Image) FillRectangle

func (img *Image) FillRectangle(gc GraphicsContext, x int, y int, width int, height int) error

FillRectangle draws a filled rectangle. The rectangle is clipped to the image bounds, so off-image or negative coordinates are handled safely.

Example

Fill a rectangle using the method-style drawing API. The GraphicsContext carries the foreground color; pass it to the draw method.

package main

import (
	"fmt"

	"github.com/craigk5n/ilibgo"
)

func main() {
	white, _ := ilibgo.AllocNamedColor("white")
	blue, _ := ilibgo.AllocNamedColor("blue")
	img := ilibgo.CreateImageWithBackground(100, 100, white)

	gc := ilibgo.CreateGraphicsContext()
	ilibgo.SetForeground(&gc, blue)
	if err := img.FillRectangle(gc, 10, 10, 50, 40); err != nil {
		panic(err)
	}

	// The pixel at (30, 30) lies inside the filled rectangle.
	r, g, b, _ := img.GetPoint(30, 30).RGBA()
	fmt.Println(r>>8, g>>8, b>>8)
}
Output:
0 0 255

func (*Image) FloodFill

func (image *Image) FloodFill(gc GraphicsContext, x int, y int) error

FloodFill replaces the contiguous region of pixels matching the color at (x, y) with the graphics context's foreground color. It uses an explicit scanline stack rather than recursion so that large regions cannot overflow the goroutine stack.

func (*Image) GetPoint

func (image *Image) GetPoint(x int, y int) Color

GetPoint returns the color at (x, y).

func (*Image) Set

func (img *Image) Set(x int, y int, c color.Color)

Set sets the pixel at (x, y) to c, satisfying draw.Image.

func (*Image) SetPoint

func (image *Image) SetPoint(gc GraphicsContext, x int, y int) error

SetPoint sets the point at (x, y) using the graphics context's foreground color.

type ImageFormat

type ImageFormat uint8

func FileType

func FileType(filename string) (ImageFormat, error)

func FormatStringToType

func FormatStringToType(formatString string) (ImageFormat, error)

Convert a string representation of an image format (typically the file extension like "png"), and convert it to the corresponding IImageFormat type. An error is returned if the type is not recognized or not supported.

type ImageOption

type ImageOption uint8
const (
	OptionNone       ImageOption = 0
	OptionGrayscale  ImageOption = 1
	OptionGreyscale  ImageOption = OptionGrayscale
	OptionAscii      ImageOption = 2 // ascii output for pbm/pgm/ppm images
	OptionInterlaced ImageOption = 4 // interlaced output (GIF)
)

type LineStyle

type LineStyle int

Line styles for use in LineStyle

const (
	LineSolid      LineStyle = 1 // default
	LineOnOffDash  LineStyle = 2 // Not yet implemented
	LineDoubleDash LineStyle = 3 // Not yet implemented
)

type Point

type Point struct {
	X int
	Y int
}

Point is an (X, Y) coordinate. Its fields are exported so callers can construct points directly (e.g. for DrawPolygon/FillPolygon), either with a struct literal (Point{X: 1, Y: 2}) or the Pt helper.

func Pt

func Pt(x int, y int) Point

Pt is a convenience constructor for a Point at (x, y).

type ScaleQuality

type ScaleQuality int

ScaleQuality selects the resampling filter used by CopyImageScaledQuality. Higher-quality filters are smoother but slower; nearest-neighbor is fastest and blockiest.

const (
	// ScaleNearestNeighbor picks the closest source pixel. Fastest and
	// blockiest; matches the behavior of CopyImageScaled.
	ScaleNearestNeighbor ScaleQuality = iota
	// ScaleApproxBiLinear is a fast bilinear approximation — a good default
	// for thumbnails.
	ScaleApproxBiLinear
	// ScaleBiLinear is full bilinear interpolation (smoother than the
	// approximate variant).
	ScaleBiLinear
	// ScaleCatmullRom is a high-quality bicubic filter; best for downscaling
	// photographs where sharpness matters.
	ScaleCatmullRom
)

type TextDirection

type TextDirection int
const (
	TextLeftToRight TextDirection = 1 // default
	TextBottomToTop TextDirection = 2
	TextTopToBottom TextDirection = 3
)

type TextStyle

type TextStyle int
const (
	TextNormal    TextStyle = 1 // default
	TextEtchedIn  TextStyle = 2 // text appears etched into background
	TextEtchedOut TextStyle = 3 // text appears etched out of background
	TextShadowed  TextStyle = 4 // text has drop shadow that fades into background
)

Directories

Path Synopsis
barcode renders a Code 39 barcode for the given text.
barcode renders a Code 39 barcode for the given text.
bdfinfo prints the metadata of an X11 BDF bitmap font: foundry, family, face name, slant, weight, spacing, pixel size, ascent/descent, and the number of defined glyphs.
bdfinfo prints the metadata of an X11 BDF bitmap font: foundry, family, face name, slant, weight, spacing, pixel size, ascent/descent, and the number of defined glyphs.
Create an go file from a BDF font file so that the BDF font can be bundled with the Go file.
Create an go file from a BDF font file so that the BDF font can be bundled with the Go file.
captcha generates a distorted-text CAPTCHA image and prints the text it encodes.
captcha generates a distorted-text CAPTCHA image and prints the text it encodes.
chart renders a simple bar chart to a PNG image.
chart renders a simple bar chart to a PNG image.
Create a PNG file that displays the font for ASCII values up to 255.
Create a PNG file that displays the font for ASCII values up to 255.
fonts
fontsheet renders a specimen catalog of the bundled BDF fonts: a sample line drawn in each font, stacked and labeled.
fontsheet renders a specimen catalog of the bundled BDF fonts: a sample line drawn in each font, stacked and labeled.
iconvert converts an image from one format to another.
iconvert converts an image from one format to another.
iresize scales an image to a new size using a selectable resampling filter.
iresize scales an image to a new size using a selectable resampling filter.
mandelbrot renders the Mandelbrot set to an image, coloring each pixel by how quickly it escapes.
mandelbrot renders the Mandelbrot set to an image, coloring each pixel by how quickly it escapes.
montage composes several images into a single labeled grid, scaling each to fit its cell while preserving aspect ratio.
montage composes several images into a single labeled grid, scaling each to fit its cell while preserving aspect ratio.
Package qr is a small, dependency-free QR Code encoder.
Package qr is a small, dependency-free QR Code encoder.
qrgen renders a QR code to a PNG image.
qrgen renders a QR code to a PNG image.
Sample app for ilibgo package.
Sample app for ilibgo package.
sparkline renders a small inline trend graph (a "sparkline") from a list of numbers to a PNG.
sparkline renders a small inline trend graph (a "sparkline") from a list of numbers to a PNG.
Build an image that contains an index of a bunch of images.
Build an image that contains an index of a bunch of images.
truetype renders text using a scalable, anti-aliased TrueType/OpenType font.
truetype renders text using a scalable, anti-aliased TrueType/OpenType font.
watermark overlays a tiled, semi-transparent text watermark onto an image.
watermark overlays a tiled, semi-transparent text watermark onto an image.
Report generator for apache2 access.log file
Report generator for apache2 access.log file

Jump to

Keyboard shortcuts

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