From f78b15a61487f459099bf4ec2f0d3950f7d38073 Mon Sep 17 00:00:00 2001 From: BobLd <38405645+BobLd@users.noreply.github.com> Date: Tue, 6 Feb 2024 11:00:49 +0000 Subject: [PATCH] Improve UnpackComponents() method performance --- .../Images/ColorSpaceDetailsByteConverter.cs | 16 ++++++++++------ 1 file changed, 10 insertions(+), 6 deletions(-) diff --git a/src/UglyToad.PdfPig/Images/ColorSpaceDetailsByteConverter.cs b/src/UglyToad.PdfPig/Images/ColorSpaceDetailsByteConverter.cs index 163149a0..61a8ce4e 100644 --- a/src/UglyToad.PdfPig/Images/ColorSpaceDetailsByteConverter.cs +++ b/src/UglyToad.PdfPig/Images/ColorSpaceDetailsByteConverter.cs @@ -51,18 +51,22 @@ private static byte[] UnpackComponents(IReadOnlyList input, int bitsPerComponent) { - IEnumerable Unpack(byte b) - { - int right = (int)Math.Pow(2, bitsPerComponent) - 1; + int end = 8 - bitsPerComponent; + var unpacked = new byte[input.Count * (int)Math.Ceiling((end + 1) / (double)bitsPerComponent)]; + int right = (int)Math.Pow(2, bitsPerComponent) - 1; + + int u = 0; + foreach (byte b in input) + { // Enumerate bits in bitsPerComponent-sized chunks from MSB to LSB, masking on the appropriate bits - for (int i = 8 - bitsPerComponent; i >= 0; i -= bitsPerComponent) + for (int i = end; i >= 0; i -= bitsPerComponent) { - yield return (byte)((b >> i) & right); + unpacked[u++] = (byte)((b >> i) & right); } } - return input.SelectMany(Unpack).ToArray(); + return unpacked; } private static byte[] RemoveStridePadding(byte[] input, int strideWidth, int imageWidth, int imageHeight, int multiplier)