ftrvxmtrx/tga
| Language | Go |
|---|---|
| License | MIT |
| Repository | github.com/ftrvxmtrx/tga |
| Documentation | pkg.go.dev/github.com/ftrvxmtrx/tga |
| Depends on | standard library only |
| Read / write | yes / yes; reads palette, grayscale and true-color (8/15/16/24/32 bits), raw or RLE; writes uncompressed grayscale or 32-bit RGBA |
tga is a small pure Go package with three functions: Decode, DecodeConfig and Encode. Decoded images are standard image.Image values, so they work with image/png, image/draw and every other Go image package. It handles origins and the TGA 2.0 attributes type (straight vs premultiplied alpha) and passes the TGA 2.0 conformance test images.
The repository hasn’t changed since 2015 and has no tagged release or go.mod, but the format hasn’t changed either and the code is complete. It doesn’t write RLE-compressed files.
Installation#
Shell
go get github.com/ftrvxmtrx/tga
Basic usage: convert TGA to PNG#
Go
package main
import (
"fmt"
"image/png"
"log"
"os"
"github.com/ftrvxmtrx/tga"
)
func main() {
in, err := os.Open("in.tga")
if err != nil {
log.Fatal(err)
}
defer in.Close()
img, err := tga.Decode(in)
if err != nil {
log.Fatal(err)
}
b := img.Bounds()
fmt.Printf("%d x %d\n", b.Dx(), b.Dy())
out, err := os.Create("out.png")
if err != nil {
log.Fatal(err)
}
defer out.Close()
if err := png.Encode(out, img); err != nil {
log.Fatal(err)
}
}
How to convert PNG to TGA#
Go
in, err := os.Open("in.png")
if err != nil {
log.Fatal(err)
}
defer in.Close()
img, err := png.Decode(in)
if err != nil {
log.Fatal(err)
}
out, err := os.Create("out.tga")
if err != nil {
log.Fatal(err)
}
defer out.Close()
// *image.Gray and *image.NRGBA are written as-is, other types are converted to NRGBA
if err := tga.Encode(out, img); err != nil {
log.Fatal(err)
}
How to get TGA width and height without decoding#
Go
f, err := os.Open("in.tga")
if err != nil {
log.Fatal(err)
}
defer f.Close()
cfg, err := tga.DecodeConfig(f)
if err != nil {
log.Fatal(err)
}
fmt.Printf("%d x %d, %T\n", cfg.Width, cfg.Height, cfg.ColorModel)
How to write a grayscale TGA#
Go
gray := image.NewGray(image.Rect(0, 0, 256, 256))
for y := 0; y < 256; y++ {
for x := 0; x < 256; x++ {
gray.SetGray(x, y, color.Gray{Y: uint8(x)})
}
}
f, _ := os.Create("gradient.tga")
defer f.Close()
tga.Encode(f, gray) // image type 3, 8 bits per pixel
Tips#
- Call
tga.Decodedirectly rather thanimage.Decode. The package registers itself with an empty magic string because TGA has no signature, so withimage.Decodeit can claim files meant for other decoders depending on import order. - Width and height are limited to 65535 pixels;
Encodereturns an error for larger images.