JT
11 months ago
6 changed files with 86 additions and 31 deletions
@ -1,14 +1,50 @@ |
|||||||
using ImageMagick; |
using KGySoft.Drawing.Imaging; |
||||||
using StabilityMatrix.Core.Models.FileInterfaces; |
using KGySoft.Drawing.SkiaSharp; |
||||||
|
using SkiaSharp; |
||||||
|
|
||||||
namespace StabilityMatrix.Core.Animation; |
namespace StabilityMatrix.Core.Animation; |
||||||
|
|
||||||
public class GifConverter |
public class GifConverter |
||||||
{ |
{ |
||||||
public static async Task ConvertWebpToGif(FilePath filePath) |
public static IEnumerable<IReadableBitmapData> EnumerateAnimatedWebp(Stream webpSource) |
||||||
{ |
{ |
||||||
using var webp = new MagickImageCollection(filePath, MagickFormat.WebP); |
using var webp = new SKManagedStream(webpSource); |
||||||
var path = filePath.ToString().Replace(".webp", ".gif"); |
using var codec = SKCodec.Create(webp); |
||||||
await webp.WriteAsync(path, MagickFormat.Gif).ConfigureAwait(false); |
|
||||||
|
var info = new SKImageInfo(codec.Info.Width, codec.Info.Height); |
||||||
|
|
||||||
|
for (var i = 0; i < codec.FrameCount; i++) |
||||||
|
{ |
||||||
|
using var tempSurface = new SKBitmap(info); |
||||||
|
|
||||||
|
codec.GetFrameInfo(i, out var frameInfo); |
||||||
|
|
||||||
|
var decodeInfo = info.WithAlphaType(frameInfo.AlphaType); |
||||||
|
|
||||||
|
tempSurface.TryAllocPixels(decodeInfo); |
||||||
|
|
||||||
|
var result = codec.GetPixels(decodeInfo, tempSurface.GetPixels(), new SKCodecOptions(i)); |
||||||
|
|
||||||
|
if (result != SKCodecResult.Success) |
||||||
|
throw new InvalidDataException($"Could not decode frame {i} of {codec.FrameCount}."); |
||||||
|
|
||||||
|
using var peekPixels = tempSurface.PeekPixels(); |
||||||
|
|
||||||
|
yield return peekPixels.GetReadableBitmapData(WorkingColorSpace.Default); |
||||||
|
} |
||||||
|
} |
||||||
|
|
||||||
|
public static Task ConvertAnimatedWebpToGifAsync(Stream webpSource, Stream gifOutput) |
||||||
|
{ |
||||||
|
var gifBitmaps = EnumerateAnimatedWebp(webpSource); |
||||||
|
|
||||||
|
return GifEncoder.EncodeAnimationAsync( |
||||||
|
new AnimatedGifConfiguration(gifBitmaps, TimeSpan.FromMilliseconds(150)) |
||||||
|
{ |
||||||
|
Quantizer = OptimizedPaletteQuantizer.Wu(alphaThreshold: 0), |
||||||
|
AllowDeltaFrames = true |
||||||
|
}, |
||||||
|
gifOutput |
||||||
|
); |
||||||
} |
} |
||||||
} |
} |
||||||
|
Loading…
Reference in new issue