diff --git a/src/ImageSharp/Formats/Tiff/Compression/Decompressors/LzwString.cs b/src/ImageSharp/Formats/Tiff/Compression/Decompressors/LzwString.cs index c56b2a683..e8a62e754 100644 --- a/src/ImageSharp/Formats/Tiff/Compression/Decompressors/LzwString.cs +++ b/src/ImageSharp/Formats/Tiff/Compression/Decompressors/LzwString.cs @@ -69,25 +69,33 @@ public class LzwString return 0; } - if (this.Length == 1) + int available = buffer.Length - offset; + if (available <= 0) { - buffer[offset] = this.value; - return 1; + return 0; + } + + int numToWrite = this.Length; + if (numToWrite > available) + { + numToWrite = available; } LzwString e = this; - int endIdx = this.Length - 1; - if (offset + endIdx >= buffer.Length) + + // if string is too long, skip bytes at the end + int toSkip = this.Length - numToWrite; + for (int i = 0; i < toSkip; i++) { - TiffThrowHelper.ThrowImageFormatException("Error reading lzw compressed stream. Either pixel buffer to write to is too small or code length is invalid!"); + e = e.previous; } - for (int i = endIdx; i >= 0; i--) + for (int i = numToWrite - 1; i >= 0; i--) { buffer[offset + i] = e.value; e = e.previous; } - return this.Length; + return numToWrite; } }