Magick.NET
| Language | C# (.NET 10 and .NET Standard 2.0) |
|---|---|
| License | Apache 2.0 (ImageMagick license for the native part) |
| Repository | github.com/dlemstra/Magick.NET |
| Documentation | docs in the repository |
| Depends on | native ImageMagick (bundled in the NuGet package) |
| Read / write | yes, all common variants including RLE and OS/2 / yes, 1-32 bit, BMP2, BMP3 and V4/V5 headers |
Magick.NET puts ImageMagick into a NuGet package with the native library included for Windows, Linux and macOS. It reads and writes more than 100 formats, so it’s a good choice when BMP is one of many formats you handle.
ImageMagick has 3 BMP writers: BMP (the default) uses a V4 or V5 header when the image has alpha, gamma or a color profile, BMP3 always writes the 40-byte Windows 3 header that every program reads, and BMP2 writes the old 12-byte header. Images converted from PNG or JPEG often carry gamma information, so use BMP3 when the output must open in old software.
Installation#
# 8 bits per channel, any CPU
dotnet add package Magick.NET-Q8-AnyCPU
Basic usage: read, resize and save a BMP#
using ImageMagick;
using var image = new MagickImage("in.bmp");
Console.WriteLine($"{image.Width} x {image.Height}, {image.Depth}-bit {image.ColorType}");
image.Resize(image.Width / 2, 0); // 0 keeps the aspect ratio
image.Write("out.bmp");
How to write a BMP that old programs can read#
MagickFormat.Bmp3 writes a classic BITMAPINFOHEADER file, 24-bit for color images:
using ImageMagick;
using var image = new MagickImage("in.png");
image.Alpha(AlphaAction.Off); // drop transparency
image.Write("out.bmp", MagickFormat.Bmp3);
How to get BMP width and height without decoding#
using ImageMagick;
var info = new MagickImageInfo("in.bmp");
Console.WriteLine($"{info.Format}: {info.Width} x {info.Height}, compression {info.Compression}");
How to write a 16-bit BMP#
BmpWriteDefines.Subtype selects a 16-bit layout (RGB565, RGB555, ARGB1555, ARGB4444), common for embedded displays:
using ImageMagick;
using ImageMagick.Formats;
using var image = new MagickImage("in.png");
image.Write("out565.bmp", new BmpWriteDefines { Subtype = BmpSubtype.RGB565 });
How to write an 8-bit palette BMP#
using ImageMagick;
using var image = new MagickImage("in.png");
image.Quantize(new QuantizeSettings { Colors = 256 });
image.ColorType = ColorType.Palette;
image.Write("palette.bmp", MagickFormat.Bmp3);
How to convert BMP to PNG#
using ImageMagick;
using var image = new MagickImage("in.bmp");
image.Write("out.png"); // format from the extension
Tips#
BmpReadDefines { IgnoreFileSize = true }reads files whose header has a wrong file size, which some writers produce.MagickImageCollectionreads ICO files, which contain BMP or PNG images in several sizes.- Width, height and sizes are
uintin Magick.NET 14 and later.