diff --git a/src/NumSharp.Bitmap/np_.extensions.cs b/src/NumSharp.Bitmap/np_.extensions.cs index c0dc7e65..47d6e608 100644 --- a/src/NumSharp.Bitmap/np_.extensions.cs +++ b/src/NumSharp.Bitmap/np_.extensions.cs @@ -220,8 +220,8 @@ public static unsafe Bitmap ToBitmap(this NDArray nd, int width, int height, Pix //if flat then initialize based on given format if (nd.ndim == 1 && format != PixelFormat.DontCare) - nd = nd.reshape(1, height, width, format.ToBytesPerPixel()); //theres a check internally for size mismatch. - + nd = nd.reshape(1, height, width, format.ToBytesPerPixel()); //theres a check internally for size mismatc + if (nd.ndim != 4) throw new ArgumentException("ndarray was expected to be of 4-dimensions, (1, bmpData.Height, bmpData.Width, bytesPerPixel)"); @@ -237,6 +237,9 @@ public static unsafe Bitmap ToBitmap(this NDArray nd, int width, int height, Pix var ret = new Bitmap(width, height, format); var bitdata = ret.LockBits(new Rectangle(0, 0, width, height), ImageLockMode.WriteOnly, format); + if (bitdata.Stride != width * format.ToBytesPerPixel()) + nd = np.concatenate((nd, np.zeros((1, height, 1, format.ToBytesPerPixel())).astype(NPTypeCode.Byte)), 2); + try { var dst = new ArraySlice(new UnmanagedMemoryBlock((byte*)bitdata.Scan0, bitdata.Stride * bitdata.Height)); diff --git a/test/NumSharp.UnitTest/NumSharp.Bitmap/BitmapWithAlphaTests.cs b/test/NumSharp.UnitTest/NumSharp.Bitmap/BitmapWithAlphaTests.cs index c4acbaa9..f95c2cd1 100644 --- a/test/NumSharp.UnitTest/NumSharp.Bitmap/BitmapWithAlphaTests.cs +++ b/test/NumSharp.UnitTest/NumSharp.Bitmap/BitmapWithAlphaTests.cs @@ -49,6 +49,16 @@ public void ToNDArray_Odd_Width() var nd = bitmap.ToNDArray(discardAlpha: false, copy: false); nd.Should().BeShaped(1, 554, 475, 3); } + + [TestMethod] + public void ToBitmap_Odd_Width() + { + var bitmap = EmbeddedBitmap("odd-width"); + var nd = bitmap.ToNDArray(discardAlpha: false, copy: false); + var bitmap2 = nd.ToBitmap(); + bitmap2.Width.Should().Be(bitmap.Width); + bitmap2.Height.Should().Be(bitmap.Height); + } [TestMethod] public void ToNDArray_Case5_flat()