microsoft/ailab · error · InvalidOperationException

Invalid image dimensions

Error message

Invalid image dimensions

What it means

buildAndVerifyImage validates an image before object detection and throws InvalidOperationException when the decoded image reports a width or height of 0. A bitmap with zero dimensions cannot be processed by the detection pipeline, so the service rejects it. This normally indicates the image bytes did not decode into a valid bitmap.

Solutions

  1. Verify the uploaded file is a valid, complete image and re-encode/re-upload it
  2. Check the code that produces the image bytes (reset MemoryStream.Position = 0 before creating the bitmap)
  3. Add a caller-side dimension check and reject zero-dimension images with a friendly message before calling the service
  4. Open the image locally (System.Drawing or an image viewer) to confirm it decodes with non-zero dimensions

Example fix

// before
var result = await service.GetPredictionAsync(imageBytes);
// after
using var check = new System.Drawing.Bitmap(new MemoryStream(imageBytes));
if (check.Width == 0 || check.Height == 0) throw new ArgumentException("Image has zero dimensions");
var result = await service.GetPredictionAsync(imageBytes);
Defensive patterns

Strategy: try-catch

Validate before calling

using var probe = System.Drawing.Image.FromStream(new MemoryStream(imageBytes));
if (probe.Width == 0 || probe.Height == 0)
    throw new ArgumentException("Uploaded image has zero dimensions");

Type guard

bool HasValidDimensions(System.Drawing.Image img) => img != null && img.Width > 0 && img.Height > 0;

Try / catch

try
{
    var result = await service.GetPredictionAsync(imageBytes);
}
catch (InvalidOperationException ex) when (ex.Message == "Invalid image dimensions")
{
    return BadRequest("The uploaded file is not a valid image with non-zero dimensions.");
}

Prevention

When it happens

Trigger: Calling the analysis API (image flow) with a byte array that decodes to a System.Drawing.Image whose Width or Height is 0 — e.g. corrupted/truncated image data or a degenerate bitmap.

Common situations: Uploading a partially downloaded/corrupt file; saving an image stream incorrectly (stream position not reset, producing a 0x0 bitmap); passing non-image bytes that a loose decoder path still accepted; generating images programmatically with uninitialized dimensions.

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 microsoft/ailab@89fe2fc620 (2026-09-13). Data as JSON: /api/errors/2c5b62fb391b73ad. Report an issue: GitHub.

Appendix: source

Thrown at Sketch2Code/Sketch2Code.Core/Services/ObjectDetectionAppService.cs:191

            return predictedObject;
        }

        private Image buildAndVerifyImage(byte[] data)
        {
            double imageWidth = 0;
            double imageHeight = 0;
            Image img;

            using (var ms = new MemoryStream(data))
            {
                img = Image.FromStream(ms);

                imageWidth = img.Width;
                imageHeight = img.Height;

                if ((imageWidth == 0) || (imageHeight == 0))
                {
                    throw new InvalidOperationException("Invalid image dimensions");
                }
            }

            return img;
        }

        public async Task SaveResults(IList<PredictedObject> predictedObjects, string id)
        {
            if (_cloudBlobClient == null) throw new InvalidOperationException("blobClient is null");
            var slices_container = $"{id}/slices";

            for (int i = 0; i < predictedObjects.Count; i++)
            {
                PredictedObject result = (PredictedObject)predictedObjects[i];
                await this.SaveResults(result.SlicedImage, slices_container, $"{result.Name}.png");
            }
        }
        public async Task SaveResults(byte[] file, string container, string fileName)

View on GitHub (pinned to 89fe2fc620)