Skip to content

Commit 49c4c1a

Browse files
BramClocktimizerOceania2018
authored andcommitted
Fixes #459 NDArray.ToBitmap() does not handle images with odd width
1 parent 62ed1aa commit 49c4c1a

File tree

2 files changed

+15
-2
lines changed

2 files changed

+15
-2
lines changed

src/NumSharp.Bitmap/np_.extensions.cs

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -220,8 +220,8 @@ public static unsafe Bitmap ToBitmap(this NDArray nd, int width, int height, Pix
220220

221221
//if flat then initialize based on given format
222222
if (nd.ndim == 1 && format != PixelFormat.DontCare)
223-
nd = nd.reshape(1, height, width, format.ToBytesPerPixel()); //theres a check internally for size mismatch.
224-
223+
nd = nd.reshape(1, height, width, format.ToBytesPerPixel()); //theres a check internally for size mismatc
224+
225225
if (nd.ndim != 4)
226226
throw new ArgumentException("ndarray was expected to be of 4-dimensions, (1, bmpData.Height, bmpData.Width, bytesPerPixel)");
227227

@@ -237,6 +237,9 @@ public static unsafe Bitmap ToBitmap(this NDArray nd, int width, int height, Pix
237237

238238
var ret = new Bitmap(width, height, format);
239239
var bitdata = ret.LockBits(new Rectangle(0, 0, width, height), ImageLockMode.WriteOnly, format);
240+
if (bitdata.Stride != width * format.ToBytesPerPixel())
241+
nd = np.concatenate((nd, np.zeros((1, height, 1, format.ToBytesPerPixel())).astype(NPTypeCode.Byte)), 2);
242+
240243
try
241244
{
242245
var dst = new ArraySlice<byte>(new UnmanagedMemoryBlock<byte>((byte*)bitdata.Scan0, bitdata.Stride * bitdata.Height));

test/NumSharp.UnitTest/NumSharp.Bitmap/BitmapWithAlphaTests.cs

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -49,6 +49,16 @@ public void ToNDArray_Odd_Width()
4949
var nd = bitmap.ToNDArray(discardAlpha: false, copy: false);
5050
nd.Should().BeShaped(1, 554, 475, 3);
5151
}
52+
53+
[TestMethod]
54+
public void ToBitmap_Odd_Width()
55+
{
56+
var bitmap = EmbeddedBitmap("odd-width");
57+
var nd = bitmap.ToNDArray(discardAlpha: false, copy: false);
58+
var bitmap2 = nd.ToBitmap();
59+
bitmap2.Width.Should().Be(bitmap.Width);
60+
bitmap2.Height.Should().Be(bitmap.Height);
61+
}
5262

5363
[TestMethod]
5464
public void ToNDArray_Case5_flat()

0 commit comments

Comments
 (0)