using System; using System.Buffers; using System.Runtime.InteropServices; using Microsoft.VisualStudio.TestTools.UnitTesting; using SixLabors.ImageSharp; using SixLabors.ImageSharp.PixelFormats; namespace ComputeSharp.D2D1.Tests.Helpers; /// /// A with helpers to load and save images. /// internal static class ImageHelper { /// /// Loads a instance from a given path. /// /// The path to load the image from. /// The resulting image width. /// The resulting image height. /// The resulting instance. public static unsafe ReadOnlyMemory LoadBitmapFromFile(string filename, out uint width, out uint height) { using Image image = Image.Load(filename); width = (uint)image.Width; height = (uint)image.Height; if (!image.DangerousTryGetSinglePixelMemory(out Memory memory)) { Assert.Inconclusive(); } return MemoryMarshal.AsBytes(memory.Span).ToArray(); } /// /// Saves a given image buffer to a target path. /// /// The path to save the image to. /// The image width. /// The image height. /// The image stride in bytes. /// The image pixel buffer. public static unsafe void SaveBitmapToFile(string filename, uint width, uint height, uint strideInBytes, byte* buffer) { byte[] pixelData = ArrayPool.Shared.Rent((int)width * (int)height * sizeof(Bgra32)); for (int i = 0; i < (int)height; i++) { ReadOnlySpan source = new(buffer + (i * (int)strideInBytes), (int)width * sizeof(Bgra32)); source.CopyTo(pixelData.AsSpan(i * (int)width * sizeof(Bgra32))); } using (Image image = Image.WrapMemory(pixelData, (int)width, (int)height)) { image.Save(filename); } ArrayPool.Shared.Return(pixelData); } }