Call Image.Identify on the file: it reads only the headers and returns the width, height, format, frame count and metadata, without decoding any pixels. For the size a phone photo is shown at, take Width and Height from Image.Load, which applies the EXIF orientation. The program below checks NASA’s “Blue Marble” photograph and a public test photo stored sideways.
dotnet new console -o ImageSize && cd ImageSize dotnet add package RecursiveAI.OneImage --version 1.10.4 curl -L -o photo.jpg \ https://images-assets.nasa.gov/image/as17-148-22727/as17-148-22727~orig.jpg repo=https://raw.githubusercontent.com/recurser/exif-orientation-examples curl -L -o phone.jpg $repo/master/Portrait_6.jpg
OneImage needs the .NET 10 SDK. Put this in Program.cs and run dotnet run:
using OneImage; foreach (string file in new[] { "photo.jpg", "phone.jpg" }) { // Headers only: fast even for very large files. ImageInfo info = Image.Identify(file); Console.WriteLine($"{file}: {info.Format.Name}, " + $"stored {info.Width}x{info.Height}, " + $"{info.Frames.Count} frame(s), " + $"orientation {info.Metadata.Orientation}"); // Load is lazy too, and reports the upright size. Image image = Image.Load(file); Console.WriteLine($"{file}: displayed {image.Width}x{image.Height}"); }
photo.jpg: jpeg, stored 4579x4579, 1 frame(s), orientation 1 photo.jpg: displayed 4579x4579 phone.jpg: jpeg, stored 1800x1200, 1 frame(s), orientation 6 phone.jpg: displayed 1200x1800
Orientations 5 to 8 swap width and height, so a phone photo stored landscape is shown portrait. Use the displayed size for layout, <img> attributes and crop coordinates; use the stored size to check a file against limits.
Check uploads without exceptions
TryIdentify returns false for data that isn’t an image, is damaged, or is over the size limits, so it is a cheap gate for uploads. It takes a path, a Stream or bytes:
using OneImage; byte[][] uploads = [File.ReadAllBytes("photo.jpg"), "not an image"u8.ToArray()]; foreach (byte[] bytes in uploads) { if (Image.TryIdentify(bytes, out ImageInfo? info)) { Console.WriteLine($"{info.Format.Name} {info.Width}x{info.Height}"); } else { Console.WriteLine("rejected: not a supported image"); } }
jpeg 4579x4579 rejected: not a supported image
Limits
- The format is detected from the content, not the file name. Formats the core doesn’t read, such as HEIC and AVIF, are rejected.
- SVG, PSD and PDF report their size only when their add-on format is registered in
LoadOptions. An SVG’s size comes from itswidth,heightorviewBox; a PDF page’s from its size in points and the render DPI. - I/O errors still throw.
TryIdentifyreturnsfalsefor bad image data, not for a missing file.
For the camera, date and GPS position, see Read EXIF data. Errors and limits are in the guide.