Skip to content

Commit

Permalink
Add play gif example (C# + SixLabors.ImageSharp)
Browse files Browse the repository at this point in the history
  • Loading branch information
KirillAldashkin committed May 29, 2023
1 parent 28fd4d4 commit abd7d30
Show file tree
Hide file tree
Showing 3 changed files with 53 additions and 0 deletions.
1 change: 1 addition & 0 deletions bindings/c#/Makefile
Expand Up @@ -22,6 +22,7 @@ build: $(RGB_LIBRARY)
dotnet build examples/MinimalExample/MinimalExample.csproj -p:SkipNative=false
dotnet build examples/PulsingBrightness/PulsingBrightness.csproj -p:SkipNative=false
dotnet build examples/Rotating3DCube/Rotating3DCube.csproj -p:SkipNative=false
dotnet build examples/PlayGIF/PlayGIF.csproj -p:SkipNative=false

$(RGB_LIBRARY):
$(MAKE) -C $(RGB_LIBDIR)
Expand Down
12 changes: 12 additions & 0 deletions bindings/c#/examples/PlayGIF/PlayGIF.csproj
@@ -0,0 +1,12 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net6.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>
<ItemGroup>
<ProjectReference Include="..\..\RPiRgbLEDMatrix.csproj" />
<PackageReference Include="SixLabors.ImageSharp" Version="3.0.1" />
</ItemGroup>
</Project>
40 changes: 40 additions & 0 deletions bindings/c#/examples/PlayGIF/Program.cs
@@ -0,0 +1,40 @@
using RPiRgbLEDMatrix;
using System.Runtime.InteropServices;
using Color = RPiRgbLEDMatrix.Color;

Console.Write("GIF path: ");
var path = Console.ReadLine()!;

using var matrix = new RGBLedMatrix(32, 2, 1);
var canvas = matrix.CreateOffscreenCanvas();

Configuration.Default.PreferContiguousImageBuffers = true;
using var image = Image.Load<Rgb24>(path);
image.Mutate(o => o.Resize(canvas.Width, canvas.Height));

var running = true;
Console.CancelKeyPress += (s, e) =>
{
running = false;
e.Cancel = true; // don't terminate, we need to dispose
};

var frame = -1;
// preprocess frames to get delays and pixel buffers
var frames = image.Frames
.Select(f => (
Pixels: f.DangerousTryGetSinglePixelMemory(out var memory) ? memory : throw new("Could not get pixel buffer"),
Delay: f.Metadata.GetGifMetadata().FrameDelay * 10
)).ToArray();

// run until user presses Ctrl+C
while (running)
{
frame = (frame + 1) % frames.Length;

var data = MemoryMarshal.Cast<Rgb24, Color>(frames[frame].Pixels.Span);
canvas.SetPixels(0, 0, canvas.Width, canvas.Height, data);

matrix.SwapOnVsync(canvas);
Thread.Sleep(frames[frame].Delay);
}

0 comments on commit abd7d30

Please sign in to comment.