{"record":{"id":"1f23f99d49963fb2","repo":"dotnet/wpf","slug":"sr-image-invalidarrayforpixel-cachedbitmap","errorCode":null,"errorMessage":"SR.Image_InvalidArrayForPixel","messagePattern":"SR\\.Image_InvalidArrayForPixel","errorType":"exception","errorClass":"ArgumentException","httpStatus":null,"severity":"error","filePath":"src/Microsoft.DotNet.Wpf/src/PresentationCore/System/Windows/Media/Imaging/CachedBitmap.cs","lineNumber":130,"sourceCode":"        {\n            ArgumentNullException.ThrowIfNull(pixels);\n\n            if (pixels.Rank != 1)\n                throw new ArgumentException(SR.Collection_BadRank, nameof(pixels));\n\n            int elementSize = -1;\n\n            if (pixels is byte[])\n                elementSize = 1;\n            else if (pixels is short[] || pixels is ushort[])\n                elementSize = 2;\n            else if (pixels is int[] || pixels is uint[] || pixels is float[])\n                elementSize = 4;\n            else if (pixels is double[])\n                elementSize = 8;\n\n            if (elementSize == -1)\n                throw new ArgumentException(SR.Image_InvalidArrayForPixel);\n\n            int destBufferSize = elementSize * pixels.Length;\n\n            fixed (byte* pixelArray = &MemoryMarshal.GetArrayDataReference(pixels))\n                InitFromMemoryPtr(pixelWidth, pixelHeight, dpiX, dpiY, pixelFormat, palette, (nint)pixelArray, destBufferSize, stride);\n        }\n\n        /// <summary>\n        /// Common implementation for CloneCore(), CloneCurrentValueCore(),\n        /// GetAsFrozenCore(), and GetCurrentValueAsFrozenCore().\n        /// </summary>\n        private void CopyCommon(CachedBitmap sourceBitmap)\n        {\n            // Avoid Animatable requesting resource updates for invalidations that occur during construction\n            Animatable_IsResourceInvalidationNecessary = false;\n\n            if (sourceBitmap._source != null)\n            {","sourceCodeStart":112,"sourceCodeEnd":148,"githubUrl":"https://github.com/dotnet/wpf/blob/81131a70a4c573cd62748a5c36908fc4d662daa9/src/Microsoft.DotNet.Wpf/src/PresentationCore/System/Windows/Media/Imaging/CachedBitmap.cs#L112-L148","documentation":"The CachedBitmap constructor only supports pixel arrays whose element size is 1, 2, 4, or 8 bytes (byte, short, ushort, int, uint, float, double). If the array is of any other element type (bool, long, decimal, object, custom struct, etc.) the constructor cannot determine the pixel element size and throws this ArgumentException.","triggerScenarios":"new CachedBitmap(long[] or bool[] or string[] or customStruct[], ...) — any Array that is 1D but not one of the seven supported element types.","commonSituations":"Using long[] for 16-bit-per-channel data (long is 8 bytes but a different type than the supported list); passing an object[] collected from LINQ; passing a struct-of-pixels array.","solutions":["Convert the array to one of the supported types: byte[], short[], ushort[], int[], uint[], float[], or double[]","Use BitConverter or a cast loop to build an int[]/byte[] from unsupported element types","Check the PixelFormat's bits-per-pixel and pick the matching element size"],"exampleFix":"// before\nlong[] pixels = LoadLongs();\nvar bmp = new CachedBitmap(pixels, w, h, 96, 96, PixelFormats.Bgr32, null, w * 4);\n// after\nint[] pixels = LoadLongs().Select(l => unchecked((int)l)).ToArray();\nvar bmp = new CachedBitmap(pixels, w, h, 96, 96, PixelFormats.Bgr32, null, w * 4);","handlingStrategy":"type-guard","validationCode":"static readonly Type[] Supported = { typeof(byte), typeof(short), typeof(ushort), typeof(int), typeof(uint), typeof(float), typeof(double) };\nstatic bool IsSupportedPixelType(Array a) => a != null && Array.IndexOf(Supported, a.GetType().GetElementType()) >= 0;","typeGuard":"static bool IsBytePixels(Array a) => a is byte[];","tryCatchPattern":"try { return new CachedBitmap(pixels, w, h, 96, 96, fmt, palette, stride); }\ncatch (ArgumentException ex) when (ex.Message.Contains(\"array\")) { pixels = ConvertToSupported(pixels); return new CachedBitmap(pixels, w, h, 96, 96, fmt, palette, stride); }","preventionTips":["Keep raw buffers as byte[] and let the PixelFormat define interpretation","Match element type to PixelFormat bits-per-pixel before constructing","Write a conversion utility that normalizes any array to one of the seven supported types"],"tags":["wpf","imaging","argument"],"backgroundTag":"type-mismatch","analyzedSha":"81131a70a4c573cd62748a5c36908fc4d662daa9","analyzedAt":"2026-09-14T10:12:48.479Z","contentChangedAt":"2026-09-14T10:12:48.479Z","schemaVersion":2},"datasetVersion":"2026-09-22T01:17:13.364Z"}