using System; using System.Runtime.InteropServices; using CommunityToolkit.Diagnostics; using ComputeSharp.Resources; using Microsoft.VisualStudio.TestTools.UnitTesting; using SixLabors.ImageSharp; using SixLabors.ImageSharp.PixelFormats; namespace ComputeSharp.Tests.Extensions; /// /// A helper class for loading images into resources. /// public static class ImagingExtensions { /// /// Creates a new instance with the specified texture data. /// /// The input pixel format used in the texture. /// The target pixel format for the returned image. /// The source instance to read data from. /// An image with the data from the input texture. public static unsafe Image ToImage(this Texture2D texture) where TFrom : unmanaged where TTo : unmanaged, IPixel { Guard.IsEqualTo(sizeof(TTo), sizeof(TFrom), nameof(TTo)); Image image = new(texture.Width, texture.Height); Assert.IsTrue(image.DangerousTryGetSinglePixelMemory(out Memory memory)); Span pixels = MemoryMarshal.Cast(memory.Span); texture.CopyTo(pixels); return image; } /// /// Creates a new instance with the specified texture data. /// /// The input pixel format used in the texture. /// The target pixel format for the returned image. /// The source instance to read data from. /// The depth layer to read the image from. /// An image with the data from the input texture at a specified depth layer. public static unsafe Image ToImage(this Texture3D texture, int depth) where TFrom : unmanaged where TTo : unmanaged, IPixel { Guard.IsEqualTo(sizeof(TTo), sizeof(TFrom), nameof(TTo)); Image image = new(texture.Width, texture.Height); Assert.IsTrue(image.DangerousTryGetSinglePixelMemory(out Memory memory)); Span pixels = MemoryMarshal.Cast(memory.Span); texture.CopyTo(pixels, 0, 0, depth, texture.Width, texture.Height, 1); return image; } }