Skip to content

Commit 58e2bc1

Browse files
committed
[DW-30] optimize PrepareByteArray use BlockCopy for faster copy
1 parent 7181b69 commit 58e2bc1

File tree

1 file changed

+26
-11
lines changed
  • IronSoftware.Drawing/IronSoftware.Drawing.Common

1 file changed

+26
-11
lines changed

IronSoftware.Drawing/IronSoftware.Drawing.Common/AnyBitmap.cs

Lines changed: 26 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -2337,20 +2337,35 @@ private bool IsThumbnail(Tiff tiff)
23372337

23382338
private ReadOnlySpan<byte> PrepareByteArray(Image<Rgba32> bmp, int[] raster, int width, int height)
23392339
{
2340-
byte[] bits = new byte[GetStride(bmp) * height];
2340+
int stride = GetStride(bmp);
2341+
byte[] bits = new byte[stride * height];
23412342

2342-
for (int y = 0; y < height; y++)
2343+
// If no extra padding exists, copy entire rows at once.
2344+
if (stride == width * 4 && true)
23432345
{
2344-
int rasterOffset = y * width;
2345-
int bitsOffset = (height - y - 1) * GetStride(bmp);
2346-
2347-
for (int x = 0; x < width; x++)
2346+
int bytesPerRow = stride;
2347+
for (int y = 0; y < height; y++)
23482348
{
2349-
int rgba = raster[rasterOffset++];
2350-
bits[bitsOffset++] = (byte)(rgba & 0xff); // R
2351-
bits[bitsOffset++] = (byte)((rgba >> 8) & 0xff); // G
2352-
bits[bitsOffset++] = (byte)((rgba >> 16) & 0xff); // B
2353-
bits[bitsOffset++] = (byte)((rgba >> 24) & 0xff); // A
2349+
int srcByteIndex = y * bytesPerRow;
2350+
int destByteIndex = (height - y - 1) * bytesPerRow;
2351+
Buffer.BlockCopy(raster, srcByteIndex, bits, destByteIndex, bytesPerRow);
2352+
}
2353+
}
2354+
else
2355+
{
2356+
// Fallback to per-pixel processing if stride includes padding.
2357+
for (int y = 0; y < height; y++)
2358+
{
2359+
int rasterOffset = y * width;
2360+
int bitsOffset = (height - y - 1) * stride;
2361+
for (int x = 0; x < width; x++)
2362+
{
2363+
int rgba = raster[rasterOffset++];
2364+
bits[bitsOffset++] = (byte)(rgba & 0xff); // R
2365+
bits[bitsOffset++] = (byte)((rgba >> 8) & 0xff); // G
2366+
bits[bitsOffset++] = (byte)((rgba >> 16) & 0xff); // B
2367+
bits[bitsOffset++] = (byte)((rgba >> 24) & 0xff); // A
2368+
}
23542369
}
23552370
}
23562371

0 commit comments

Comments
 (0)