ImageSharp
| Language | C# (.NET) |
|---|---|
| License | Six Labors Split License (Apache 2.0 for open source, non-profits and companies under $1M annual revenue; commercial license otherwise; not OSI-approved) |
| Repository | github.com/SixLabors/ImageSharp |
| Documentation | docs.sixlabors.com |
| Depends on | nothing native |
| Read / write | yes / yes, 8 (grayscale), 16, 24 and 32 bits per pixel, raw or RLE |
ImageSharp is a fully managed image library: no native binaries, the same code on Windows, Linux and macOS. Its TGA decoder reads palette, grayscale and true-color files, raw and RLE, and handles the origin bit. The TgaEncoder writes 8, 16, 24 or 32 bits per pixel with optional RLE compression.
Check the license before using it in a commercial product: the Six Labors Split License requires a paid license for larger companies.
Installation#
Shell
dotnet add package SixLabors.ImageSharp
Basic usage: read a TGA and save it as PNG#
C#
using SixLabors.ImageSharp;
using Image image = Image.Load("in.tga");
Console.WriteLine($"{image.Width} x {image.Height}");
image.SaveAsPng("out.png");
Image.Load detects the format from the content, so any extension works.
How to save a 32-bit TGA with RLE compression#
C#
using SixLabors.ImageSharp;
using SixLabors.ImageSharp.Formats.Tga;
using Image image = Image.Load("in.png");
image.SaveAsTga("out.tga", new TgaEncoder
{
BitsPerPixel = TgaBitsPerPixel.Bit32, // Bit8, Bit16, Bit24, Bit32
Compression = TgaCompression.RunLength, // or TgaCompression.None
});
Without an encoder, SaveAsTga keeps the bit depth of the source TGA (or picks one from the pixel format).
How to get TGA size and bit depth without decoding#
Image.Identify reads only the header:
C#
using SixLabors.ImageSharp;
using SixLabors.ImageSharp.Formats.Tga;
ImageInfo info = Image.Identify("in.tga");
TgaMetadata tga = info.Metadata.GetTgaMetadata();
Console.WriteLine($"{info.Width} x {info.Height}, {tga.BitsPerPixel}, alpha bits: {tga.AlphaChannelBits}");
How to read TGA pixels#
C#
using SixLabors.ImageSharp;
using SixLabors.ImageSharp.PixelFormats;
using Image<Rgba32> image = Image.Load<Rgba32>("in.tga");
Rgba32 topLeft = image[0, 0]; // row 0 is the top row, whatever the file's origin
Console.WriteLine($"R={topLeft.R} G={topLeft.G} B={topLeft.B} A={topLeft.A}");
How to resize a TGA texture#
C#
using SixLabors.ImageSharp;
using SixLabors.ImageSharp.Processing;
using Image image = Image.Load("in.tga");
image.Mutate(x => x.Resize(image.Width / 2, image.Height / 2));
image.SaveAsTga("half.tga");
Tips#
- TGA has no magic bytes, so ImageSharp’s format detection relies on header checks. If detection fails, decode explicitly with
TgaDecoder.Instance.Decode(new DecoderOptions(), stream). - Use
Image.LoadAsyncandSaveAsTgaAsyncin web servers.