dotnet/machinelearning · error · ArgumentException

Path has invalid image file extension.

Error message

Path has invalid image file extension.

What it means

MLImage.Save infers the encoding format from the file extension via a lookup table (_extensionToEncodingFormat, covering Jpeg/Png/Webp). If the extension is missing or not one of the supported ones, ArgumentException is thrown.

Source

Thrown at src/Microsoft.ML.ImageAnalytics/MLImage.cs:240

                ThrowInvalidOperationExceptionIfDisposed();
                Debug.Assert(_image.Info.BitsPerPixel == 32);
                return _image.Info.BitsPerPixel;
            }
        }

        /// <summary>
        /// Save the current image to a file.
        /// </summary>
        /// <param name="imagePath">The path of the file to save the image to.</param>
        /// <remarks>The saved image encoding will be detected from the file extension.</remarks>
        public void Save(string imagePath)
        {
            ThrowInvalidOperationExceptionIfDisposed();
            string ext = Path.GetExtension(imagePath);

            if (!_extensionToEncodingFormat.TryGetValue(ext, out SKEncodedImageFormat encodingFormat))
            {
                throw new ArgumentException($"Path has invalid image file extension.", nameof(imagePath));
            }

            using SKData data = _image.Encode(encodingFormat, 100);
            if (data is null)
            {
                throw new ArgumentException($"Saving image with the format '{ext}' is not supported. Try save it with `Jpeg`, `Png`, or `Webp` format.", nameof(imagePath));
            }

            using var stream = new FileStream(imagePath, FileMode.Create, FileAccess.Write);
            data.SaveTo(stream);
        }

        /// <summary>
        /// Disposes the image.
        /// </summary>
        public void Dispose()
        {
            if (_image != null)

View on GitHub (pinned to 7b76e69cf9)

Solutions

  1. Use a .jpg, .png, or .webp extension in the save path
  2. Convert the image first if another format is required
  3. Normalize extension casing and ensure the path includes an extension

Example fix

// before
image.Save(Path.Combine(dir, name)); // no extension
// after
image.Save(Path.Combine(dir, name + ".png"));
Defensive patterns

Strategy: validation

Validate before calling

string ext = Path.GetExtension(path).ToLowerInvariant();
if (ext is not ".jpg" and not ".jpeg" and not ".png" and not ".webp")
    path = Path.ChangeExtension(path, ".png");

Type guard

bool IsSaveableExtension(string p) => new[]{".jpg",".jpeg",".png",".webp"}.Contains(Path.GetExtension(p ?? "").ToLowerInvariant());

Try / catch

try { image.Save(path); } catch (ArgumentException ex) when (ex.Message.Contains("invalid image file extension")) { image.Save(Path.ChangeExtension(path, ".png")); }

Prevention

When it happens

Trigger: Calling image.Save(path) where Path.GetExtension(path) is not .jpg/.jpeg/.png/.webp — e.g. saving to '.bmp', '.tif', extensionless paths, or a path with a trailing dot.

Common situations: Saving to an extension from another library (BMP/TIFF), deriving paths from user input without normalizing extension case, or omitting the extension entirely.

Understand the failure class

Background: "Must be a positive integer", "Invalid value", "Unsupported": the invalid-argument-value error family, when a library rejects the value you pass — this error's family across 35 libraries.

Related errors


AI-assisted analysis of dotnet/machinelearning@7b76e69cf9 (2026-09-11). Data as JSON: /api/errors/8aa4d72d849bf7fa. Report an issue: GitHub.