// Copyright (c) ppy Pty Ltd . Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. #nullable enable using System.Buffers; using SixLabors.ImageSharp; using SixLabors.ImageSharp.PixelFormats; namespace osu.Framework.Extensions.ImageExtensions { public static class ImageExtensions { /// /// Creates a contiguous and read-only span from the pixels of an . /// Useful for retrieving unmanaged pointers to the entire pixel data of the for marshalling. /// /// /// The returned must be disposed when usage is finished. /// /// The . /// The type of pixels in . /// The . public static ReadOnlyPixelSpan CreateReadOnlyPixelSpan(this Image image) where TPixel : unmanaged, IPixel => new ReadOnlyPixelSpan(image); /// /// Creates a contiguous and read-only memory from the pixels of an . /// Useful for retrieving unmanaged pointers to the entire pixel data of the for marshalling. /// /// /// The returned must be disposed when usage is finished. /// /// The . /// The type of pixels in . /// The . public static ReadOnlyPixelMemory CreateReadOnlyPixelMemory(this Image image) where TPixel : unmanaged, IPixel => new ReadOnlyPixelMemory(image); /// /// Creates a new contiguous memory buffer from the pixels in an . /// /// /// The returned must be disposed when usage is finished. /// /// The . /// The type of pixels in . /// The , containing the contiguous pixel memory. internal static IMemoryOwner CreateContiguousMemory(this Image image) where TPixel : unmanaged, IPixel { var allocatedOwner = SixLabors.ImageSharp.Configuration.Default.MemoryAllocator.Allocate(image.Width * image.Height); var allocatedSpan = allocatedOwner.Memory.Span; for (int r = 0; r < image.Height; r++) image.GetPixelRowSpan(r).CopyTo(allocatedSpan.Slice(r * image.Width)); return allocatedOwner; } } }