MagicBytes
Detects MIME types from binary content using magic byte signatures. Only the first 16 bytes of input are required, making resolution fast regardless of file size.
Installation
def deps do
[
{:magic_bytes, "~> 0.1.0"}
]
endUsage
From a file path
MagicBytes.from_path("image.png")
#=> {:ok, "image/png"}
MagicBytes.from_path("archive.tar.gz")
#=> {:ok, "application/gzip"}
MagicBytes.from_path("/nonexistent/file")
#=> {:error, :unreadable}From a binary
Useful when bytes are already in memory — e.g. an upload buffer or a database blob. Only the leading bytes matter; passing the full content works but is not required.
MagicBytes.from_binary(<<0xFF, 0xD8, 0xFF, 0xE0>>)
#=> {:ok, "image/jpeg"}
MagicBytes.from_binary(file_contents)
#=> {:ok, "application/pdf"}
MagicBytes.from_binary(<<0x00, 0x00, 0x00, 0x00>>)
#=> {:error, :unknown}From a stream
Chunks are accumulated until the required 16 bytes are accumulated and run. The stream is not fully consumed.
File.stream!("video.mkv", 1024)
|> MagicBytes.from_stream()
#=> {:ok, "video/x-matroska"}Guards
For prefix-based signatures a corresponding guard macro is generated and
re-exported from MagicBytes. Guard names follow the pattern
is_<mime_type> with / and - replaced by _.
require MagicBytes
def process(bin) when MagicBytes.is_image_jpeg(bin), do: ...
def process(bin) when MagicBytes.is_image_png(bin), do: ...
def process(bin) when MagicBytes.is_application_pdf(bin), do: ...
def process(_bin), do: {:error, :unsupported}
Guards also work as boolean expressions outside when clauses:
require MagicBytes
MagicBytes.is_application_gzip(data) #=> true | false
Guards are not generated for container-format signatures where the
distinguishing bytes appear at a non-zero offset (WebP, WAV, AVI, AIFF,
MP4, HEIC, AVIF, QuickTime). Use from_binary/1 for those formats.
Supported formats
| Category | MIME types |
|---|---|
| Images | image/jpegimage/pngimage/gifimage/webpimage/bmpimage/tiffimage/x-iconimage/vnd.adobe.photoshopimage/heicimage/avif |
| Audio | audio/mpegaudio/flacaudio/oggaudio/wavaudio/aiffaudio/mp4 |
| Video | video/mp4video/quicktimevideo/x-matroskavideo/x-flvvideo/x-msvideo |
| Documents | application/pdfapplication/zipapplication/x-cfbapplication/rtf |
| Archives | application/x-rar-compressedapplication/x-7z-compressedapplication/gzipapplication/x-bzip2application/x-xzapplication/zstd |
| Executables | application/x-elfapplication/x-msdownloadapplication/x-mach-binaryapplication/wasm |
| Fonts | font/wofffont/woff2font/otffont/ttf |
| Database | application/x-sqlite3 |