using System;
using System.Diagnostics.Contracts;
using System.Runtime.InteropServices;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using SixLabors.ImageSharp;
using ImageSharpRgba32 = SixLabors.ImageSharp.PixelFormats.Rgba32;
namespace ComputeSharp.Tests.Extensions
{
///
/// A helper class for loading images into resources.
///
public static class ImagingExtensions
{
///
/// Allocates a new instance with the specified texture data.
///
/// The target instance to allocate the texture for.
/// The path of the texture to load.
/// A texture with the data from the image at the specified path.
[Pure]
public static ReadOnlyTexture2D LoadTexture(this GraphicsDevice device, string path)
{
using Image image = Image.Load(path);
Assert.IsTrue(image.TryGetSinglePixelSpan(out Span span));
Span pixels = MemoryMarshal.Cast(span);
return device.AllocateReadOnlyTexture2D(pixels, image.Width, image.Height);
}
///
/// Creates a new instance with the specified texture data.
///
/// The source instance to read data from.
/// An image with the data from the input texture.
[Pure]
public static Image ToImage(this ReadWriteTexture2D texture)
{
Image image = new(texture.Width, texture.Height);
Assert.IsTrue(image.TryGetSinglePixelSpan(out Span span));
Span pixels = MemoryMarshal.Cast(span);
texture.CopyTo(pixels);
return image;
}
}
}