From cfdd95f0790013b241c4bc547d23aa7e058365ef Mon Sep 17 00:00:00 2001 From: Darth Affe Date: Sun, 21 Jul 2024 17:29:14 +0200 Subject: [PATCH] Added Wrap-Methods to Image and RefImage for allocation free creation --- HPPH/Images/Image.cs | 8 ++++++++ HPPH/Images/RefImage.cs | 11 +++++++++++ 2 files changed, 19 insertions(+) diff --git a/HPPH/Images/Image.cs b/HPPH/Images/Image.cs index 6f9e79d..f221c15 100644 --- a/HPPH/Images/Image.cs +++ b/HPPH/Images/Image.cs @@ -125,6 +125,14 @@ public sealed class Image : IImage, IEquatable> return new Image(data, 0, 0, width, height, stride); } + public static Image Wrap(byte[] buffer, int width, int height, int stride) + { + if (stride < width) throw new ArgumentException("Stride can't be smaller than width."); + if (buffer.Length < (height * stride)) throw new ArgumentException("Not enough data in the buffer."); + + return new Image(buffer, 0, 0, width, height, stride); + } + /// public IImage ConvertTo() where TColor : struct, IColor diff --git a/HPPH/Images/RefImage.cs b/HPPH/Images/RefImage.cs index 60c74ce..8772a10 100644 --- a/HPPH/Images/RefImage.cs +++ b/HPPH/Images/RefImage.cs @@ -86,6 +86,17 @@ public readonly ref struct RefImage #region Methods + public static RefImage Wrap(ReadOnlySpan buffer, int width, int height) + => Wrap(MemoryMarshal.AsBytes(buffer), width, height, width * T.ColorFormat.BytesPerPixel); + + public static RefImage Wrap(ReadOnlySpan buffer, int width, int height, int stride) + { + if (stride < width) throw new ArgumentException("Stride can't be smaller than width."); + if (buffer.Length < (height * stride)) throw new ArgumentException("Not enough data in the buffer."); + + return new RefImage(buffer, 0, 0, width, height, stride); + } + /// /// Copies the contents of this into a destination instance. ///