1
1
// Copyright (c) Six Labors.
2
2
// Licensed under the Six Labors Split License.
3
3
4
+ using System . Buffers ;
4
5
using System . Buffers . Binary ;
5
6
using System . Runtime . CompilerServices ;
6
7
using SixLabors . ImageSharp . Memory ;
@@ -14,10 +15,16 @@ namespace SixLabors.ImageSharp.Formats.Qoi;
14
15
public class QoiEncoderCore : IImageEncoderInternals
15
16
{
16
17
private readonly QoiEncoder encoder ;
18
+ private readonly MemoryAllocator memoryAllocator ;
19
+
17
20
/// <summary>
18
21
/// Initializes a new instance of the <see cref="QoiEncoderCore"/> class.
19
22
/// </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
+ }
21
28
22
29
/// <inheritdoc />
23
30
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
27
34
Guard . NotNull ( stream , nameof ( stream ) ) ;
28
35
29
36
this . WriteHeader ( image , stream ) ;
30
- WritePixels ( image , stream ) ;
37
+ this . WritePixels ( image , stream ) ;
31
38
WriteEndOfStream ( stream ) ;
32
39
stream . Flush ( ) ;
33
40
}
@@ -50,21 +57,22 @@ private void WriteHeader(Image image, Stream stream)
50
57
stream . WriteByte ( ( byte ) qoiColorSpace ) ;
51
58
}
52
59
53
- private static void WritePixels < TPixel > ( Image < TPixel > image , Stream stream )
60
+ private void WritePixels < TPixel > ( Image < TPixel > image , Stream stream )
54
61
where TPixel : unmanaged, IPixel < TPixel >
55
62
{
56
63
// 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 ( ) ;
58
66
Rgba32 previousPixel = new ( 0 , 0 , 0 , 255 ) ;
59
67
Rgba32 currentRgba32 = default ;
60
68
Buffer2D < TPixel > pixels = image . Frames [ 0 ] . PixelBuffer ;
61
69
62
70
for ( int i = 0 ; i < pixels . Height ; i ++ )
63
71
{
72
+ Span < TPixel > row = pixels . DangerousGetRowSpan ( i ) ;
64
73
for ( int j = 0 ; j < pixels . Width && i < pixels . Height ; j ++ )
65
74
{
66
75
// We get the RGBA value from pixels
67
- Span < TPixel > row = pixels . DangerousGetRowSpan ( i ) ;
68
76
TPixel currentPixel = pixels [ j , i ] ;
69
77
currentPixel . ToRgba32 ( ref currentRgba32 ) ;
70
78
0 commit comments