From 23c692656584b0481563250cddea33710245eb0f Mon Sep 17 00:00:00 2001 From: Brian Popow Date: Mon, 9 Aug 2021 13:20:05 +0200 Subject: [PATCH] Add padding when width and height are not multiples of ChromaSubsampleHoriz and ChromaSubsampleVert --- .../YCbCrTiffColor{TPixel}.cs | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-) diff --git a/src/ImageSharp/Formats/Tiff/PhotometricInterpretation/YCbCrTiffColor{TPixel}.cs b/src/ImageSharp/Formats/Tiff/PhotometricInterpretation/YCbCrTiffColor{TPixel}.cs index 7a7e1ad87..b6944168d 100644 --- a/src/ImageSharp/Formats/Tiff/PhotometricInterpretation/YCbCrTiffColor{TPixel}.cs +++ b/src/ImageSharp/Formats/Tiff/PhotometricInterpretation/YCbCrTiffColor{TPixel}.cs @@ -30,7 +30,11 @@ namespace SixLabors.ImageSharp.Formats.Tiff.PhotometricInterpretation ReadOnlySpan ycbcrData = data; if (this.ycbcrSubSampling != null && !(this.ycbcrSubSampling[0] == 1 && this.ycbcrSubSampling[1] == 1)) { - using IMemoryOwner tmpBuffer = this.memoryAllocator.Allocate(data.Length); + // 4 extra rows and columns for possible padding. + int paddedWidth = width + 4; + int paddedHeight = height + 4; + int requiredBytes = paddedWidth * paddedHeight * 3; + using IMemoryOwner tmpBuffer = this.memoryAllocator.Allocate(requiredBytes); Span tmpBufferSpan = tmpBuffer.GetSpan(); ReverseChromaSubSampling(width, height, this.ycbcrSubSampling[0], this.ycbcrSubSampling[1], data, tmpBufferSpan); ycbcrData = tmpBufferSpan; @@ -53,6 +57,10 @@ namespace SixLabors.ImageSharp.Formats.Tiff.PhotometricInterpretation private static void ReverseChromaSubSampling(int width, int height, int horizontalSubSampling, int verticalSubSampling, ReadOnlySpan source, Span destination) { + // If width and height are not multiples of ChromaSubsampleHoriz and ChromaSubsampleVert respectively, + // then the source data will be padded. + width += width % horizontalSubSampling; + height += height % verticalSubSampling; int blockWidth = width / horizontalSubSampling; int blockHeight = height / verticalSubSampling; int cbCrOffsetInBlock = horizontalSubSampling * verticalSubSampling;