Skip to content

Commit cdd041c

Browse files
committed
Ensure Span length of source and destination are equal during pixel conversions.
1 parent 0e0dc2a commit cdd041c

1 file changed

Lines changed: 11 additions & 6 deletions

File tree

src/ImageSharp/Formats/Bmp/BmpEncoderCore.cs

Lines changed: 11 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -262,16 +262,18 @@ private void Write32Bit<TPixel>(Stream stream, Buffer2D<TPixel> pixels)
262262
private void Write24Bit<TPixel>(Stream stream, Buffer2D<TPixel> pixels)
263263
where TPixel : unmanaged, IPixel<TPixel>
264264
{
265-
using (IManagedByteBuffer row = this.AllocateRow(pixels.Width, 3))
265+
int width = pixels.Width;
266+
int rowBytesWithoutPadding = width * 3;
267+
using (IManagedByteBuffer row = this.AllocateRow(width, 3))
266268
{
267269
for (int y = pixels.Height - 1; y >= 0; y--)
268270
{
269271
Span<TPixel> pixelSpan = pixels.GetRowSpan(y);
270272
PixelOperations<TPixel>.Instance.ToBgr24Bytes(
271273
this.configuration,
272274
pixelSpan,
273-
row.GetSpan(),
274-
pixelSpan.Length);
275+
row.Slice(0, rowBytesWithoutPadding),
276+
width);
275277
stream.Write(row.Array, 0, row.Length());
276278
}
277279
}
@@ -286,7 +288,9 @@ private void Write24Bit<TPixel>(Stream stream, Buffer2D<TPixel> pixels)
286288
private void Write16Bit<TPixel>(Stream stream, Buffer2D<TPixel> pixels)
287289
where TPixel : unmanaged, IPixel<TPixel>
288290
{
289-
using (IManagedByteBuffer row = this.AllocateRow(pixels.Width, 2))
291+
int width = pixels.Width;
292+
int rowBytesWithoutPadding = width * 2;
293+
using (IManagedByteBuffer row = this.AllocateRow(width, 2))
290294
{
291295
for (int y = pixels.Height - 1; y >= 0; y--)
292296
{
@@ -295,7 +299,7 @@ private void Write16Bit<TPixel>(Stream stream, Buffer2D<TPixel> pixels)
295299
PixelOperations<TPixel>.Instance.ToBgra5551Bytes(
296300
this.configuration,
297301
pixelSpan,
298-
row.GetSpan(),
302+
row.Slice(0, rowBytesWithoutPadding),
299303
pixelSpan.Length);
300304

301305
stream.Write(row.Array, 0, row.Length());
@@ -341,7 +345,8 @@ private void Write8BitColor<TPixel>(Stream stream, ImageFrame<TPixel> image, Spa
341345
using IndexedImageFrame<TPixel> quantized = frameQuantizer.BuildPaletteAndQuantizeFrame(image, image.Bounds());
342346

343347
ReadOnlySpan<TPixel> quantizedColors = quantized.Palette.Span;
344-
PixelOperations<TPixel>.Instance.ToBgra32(this.configuration, quantizedColors, MemoryMarshal.Cast<byte, Bgra32>(colorPalette));
348+
var quantizedColorBytes = quantizedColors.Length * 4;
349+
PixelOperations<TPixel>.Instance.ToBgra32(this.configuration, quantizedColors, MemoryMarshal.Cast<byte, Bgra32>(colorPalette.Slice(0, quantizedColorBytes)));
345350
Span<uint> colorPaletteAsUInt = MemoryMarshal.Cast<byte, uint>(colorPalette);
346351
for (int i = 0; i < colorPaletteAsUInt.Length; i++)
347352
{

0 commit comments

Comments
 (0)