Skip to content

Commit eb63882

Browse files
committed
Handle edge case when we are at the last byte position, but not all pixels have been written
1 parent 928db20 commit eb63882

File tree

1 file changed

+29
-11
lines changed

1 file changed

+29
-11
lines changed

src/ImageSharp/Formats/Tiff/Compression/Decompressors/T4TiffCompression.cs

Lines changed: 29 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,8 @@ internal class T4TiffCompression : TiffBaseDecompressor
2020

2121
private readonly byte blackValue;
2222

23+
private readonly int width;
24+
2325
/// <summary>
2426
/// Initializes a new instance of the <see cref="T4TiffCompression" /> class.
2527
/// </summary>
@@ -34,7 +36,7 @@ public T4TiffCompression(MemoryAllocator allocator, TiffFillOrder fillOrder, int
3436
{
3537
this.faxCompressionOptions = faxOptions;
3638
this.FillOrder = fillOrder;
37-
39+
this.width = width;
3840
bool isWhiteZero = photometricInterpretation == TiffPhotometricInterpretation.WhiteIsZero;
3941
this.whiteValue = (byte)(isWhiteZero ? 0 : 1);
4042
this.blackValue = (byte)(isWhiteZero ? 1 : 0);
@@ -58,22 +60,17 @@ protected override void Decompress(BufferedReadStream stream, int byteCount, Spa
5860

5961
buffer.Clear();
6062
uint bitsWritten = 0;
63+
uint pixelWritten = 0;
6164
while (bitReader.HasMoreData)
6265
{
6366
bitReader.ReadNextRun();
6467

6568
if (bitReader.RunLength > 0)
6669
{
67-
if (bitReader.IsWhiteRun)
68-
{
69-
BitWriterUtils.WriteBits(buffer, (int)bitsWritten, bitReader.RunLength, this.whiteValue);
70-
bitsWritten += bitReader.RunLength;
71-
}
72-
else
73-
{
74-
BitWriterUtils.WriteBits(buffer, (int)bitsWritten, bitReader.RunLength, this.blackValue);
75-
bitsWritten += bitReader.RunLength;
76-
}
70+
this.WritePixelRun(buffer, bitReader, bitsWritten);
71+
72+
bitsWritten += bitReader.RunLength;
73+
pixelWritten += bitReader.RunLength;
7774
}
7875

7976
if (bitReader.IsEndOfScanLine)
@@ -85,8 +82,29 @@ protected override void Decompress(BufferedReadStream stream, int byteCount, Spa
8582
BitWriterUtils.WriteBits(buffer, (int)bitsWritten, pad, 0);
8683
bitsWritten += pad;
8784
}
85+
86+
pixelWritten = 0;
8887
}
8988
}
89+
90+
// Edge case for when we are at the last byte, but there are still some unwritten pixels left.
91+
if (pixelWritten > 0 && pixelWritten < this.width)
92+
{
93+
bitReader.ReadNextRun();
94+
this.WritePixelRun(buffer, bitReader, bitsWritten);
95+
}
96+
}
97+
98+
private void WritePixelRun(Span<byte> buffer, T4BitReader bitReader, uint bitsWritten)
99+
{
100+
if (bitReader.IsWhiteRun)
101+
{
102+
BitWriterUtils.WriteBits(buffer, (int)bitsWritten, bitReader.RunLength, this.whiteValue);
103+
}
104+
else
105+
{
106+
BitWriterUtils.WriteBits(buffer, (int)bitsWritten, bitReader.RunLength, this.blackValue);
107+
}
90108
}
91109

92110
/// <inheritdoc/>

0 commit comments

Comments
 (0)