Browse Source

Pack the bits directly in GifImageDescriptor

This avoids the array allocation in PackedField
af/merge-core
Jason Nelson 8 years ago
parent
commit
242b61fb40
  1. 2
      src/ImageSharp/Formats/Gif/GifEncoderCore.cs
  2. 38
      src/ImageSharp/Formats/Gif/Sections/GifImageDescriptor.cs
  3. 25
      tests/ImageSharp.Tests/Formats/Gif/Sections/GifImageDescriptorTests.cs

2
src/ImageSharp/Formats/Gif/GifEncoderCore.cs

@ -290,7 +290,7 @@ namespace SixLabors.ImageSharp.Formats.Gif
localColorTableFlag: true,
interfaceFlag: false,
sortFlag: false,
localColorTableSize: this.bitDepth); // Note: we subtract 1 from the colorTableSize writing
localColorTableSize: (byte)this.bitDepth); // Note: we subtract 1 from the colorTableSize writing
var descriptor = new GifImageDescriptor(
left: 0,

38
src/ImageSharp/Formats/Gif/Sections/GifImageDescriptor.cs

@ -81,16 +81,36 @@ namespace SixLabors.ImageSharp.Formats.Gif
return MemoryMarshal.Cast<byte, GifImageDescriptor>(buffer)[0];
}
public static byte GetPackedValue(bool localColorTableFlag, bool interfaceFlag, bool sortFlag, int localColorTableSize)
public static byte GetPackedValue(bool localColorTableFlag, bool interfaceFlag, bool sortFlag, byte localColorTableSize)
{
var field = default(PackedField);
field.SetBit(0, localColorTableFlag); // 0: Local color table flag = 1 (LCT used)
field.SetBit(1, interfaceFlag); // 1: Interlace flag 0
field.SetBit(2, sortFlag); // 2: Sort flag 0
field.SetBits(5, 3, localColorTableSize - 1); // 3-4: Reserved, 5-7 : LCT size. 2^(N+1)
return field.Byte;
/*
Local Color Table Flag | 1 Bit
Interlace Flag | 1 Bit
Sort Flag | 1 Bit
Reserved | 2 Bits
Size of Local Color Table | 3 Bits
*/
byte value = 0;
if (localColorTableFlag)
{
value |= 1 << 7;
}
if (interfaceFlag)
{
value |= 1 << 6;
}
if (sortFlag)
{
value |= 1 << 5;
}
value |= (byte)(localColorTableSize - 1);
return value;
}
}
}

25
tests/ImageSharp.Tests/Formats/Gif/Sections/GifImageDescriptorTests.cs

@ -0,0 +1,25 @@
// Copyright (c) Six Labors and contributors.
// Licensed under the Apache License, Version 2.0.
using SixLabors.ImageSharp.Formats.Gif;
using Xunit;
namespace SixLabors.ImageSharp.Tests.Formats.Gif
{
public class GifImageDescriptorTests
{
[Fact]
public void TestPackedValue()
{
Assert.Equal(128, GifImageDescriptor.GetPackedValue(true, false, false, 1)); // localColorTable
Assert.Equal(64, GifImageDescriptor.GetPackedValue(false, true, false, 1)); // interfaceFlag
Assert.Equal(32, GifImageDescriptor.GetPackedValue(false, false, true, 1)); // sortFlag
Assert.Equal(224, GifImageDescriptor.GetPackedValue(true, true, true, 1)); // all
Assert.Equal(7, GifImageDescriptor.GetPackedValue(false, false, false, 8));
Assert.Equal(227, GifImageDescriptor.GetPackedValue(true, true, true, 4));
Assert.Equal(231, GifImageDescriptor.GetPackedValue(true, true, true, 8));
}
}
}
Loading…
Cancel
Save