11// Copyright (c) Six Labors.
22// Licensed under the Six Labors Split License.
33
4+ using System . Buffers ;
45using System . Buffers . Binary ;
56using System . Runtime . CompilerServices ;
67using SixLabors . ImageSharp . Memory ;
@@ -14,10 +15,16 @@ namespace SixLabors.ImageSharp.Formats.Qoi;
1415public class QoiEncoderCore : IImageEncoderInternals
1516{
1617 private readonly QoiEncoder encoder ;
18+ private readonly MemoryAllocator memoryAllocator ;
19+
1720 /// <summary>
1821 /// Initializes a new instance of the <see cref="QoiEncoderCore"/> class.
1922 /// </summary>
20- public QoiEncoderCore ( QoiEncoder encoder ) => this . encoder = encoder ;
23+ public QoiEncoderCore ( QoiEncoder encoder , MemoryAllocator memoryAllocator )
24+ {
25+ this . encoder = encoder ;
26+ this . memoryAllocator = memoryAllocator ;
27+ }
2128
2229 /// <inheritdoc />
2330 public void Encode < TPixel > ( Image < TPixel > image , Stream stream , CancellationToken cancellationToken )
@@ -27,7 +34,7 @@ public void Encode<TPixel>(Image<TPixel> image, Stream stream, CancellationToken
2734 Guard . NotNull ( stream , nameof ( stream ) ) ;
2835
2936 this . WriteHeader ( image , stream ) ;
30- WritePixels ( image , stream ) ;
37+ this . WritePixels ( image , stream ) ;
3138 WriteEndOfStream ( stream ) ;
3239 stream . Flush ( ) ;
3340 }
@@ -50,21 +57,22 @@ private void WriteHeader(Image image, Stream stream)
5057 stream . WriteByte ( ( byte ) qoiColorSpace ) ;
5158 }
5259
53- private static void WritePixels < TPixel > ( Image < TPixel > image , Stream stream )
60+ private void WritePixels < TPixel > ( Image < TPixel > image , Stream stream )
5461 where TPixel : unmanaged, IPixel < TPixel >
5562 {
5663 // Start image encoding
57- Rgba32 [ ] previouslySeenPixels = new Rgba32 [ 64 ] ;
64+ using IMemoryOwner < Rgba32 > previouslySeenPixelsBuffer = this . memoryAllocator . Allocate < Rgba32 > ( 64 ) ;
65+ Span < Rgba32 > previouslySeenPixels = previouslySeenPixelsBuffer . GetSpan ( ) ;
5866 Rgba32 previousPixel = new ( 0 , 0 , 0 , 255 ) ;
5967 Rgba32 currentRgba32 = default ;
6068 Buffer2D < TPixel > pixels = image . Frames [ 0 ] . PixelBuffer ;
6169
6270 for ( int i = 0 ; i < pixels . Height ; i ++ )
6371 {
72+ Span < TPixel > row = pixels . DangerousGetRowSpan ( i ) ;
6473 for ( int j = 0 ; j < pixels . Width && i < pixels . Height ; j ++ )
6574 {
6675 // We get the RGBA value from pixels
67- Span < TPixel > row = pixels . DangerousGetRowSpan ( i ) ;
6876 TPixel currentPixel = pixels [ j , i ] ;
6977 currentPixel . ToRgba32 ( ref currentRgba32 ) ;
7078
0 commit comments