| | 1 | | using System.Buffers; |
| | 2 | | using System.IO; |
| | 3 | | using System.Linq; |
| | 4 | | using Imagini.Drawing; |
| | 5 | | using SixLabors.ImageSharp; |
| | 6 | | using SixLabors.ImageSharp.Advanced; |
| | 7 | | using SixLabors.ImageSharp.Formats; |
| | 8 | | using SixLabors.ImageSharp.PixelFormats; |
| | 9 | |
|
| | 10 | | /// <summary> |
| | 11 | | /// ImageSharp integration module. |
| | 12 | | /// </summary> |
| | 13 | | namespace Imagini.ImageSharp |
| | 14 | | { |
| | 15 | | /// <summary> |
| | 16 | | /// Contains various functions to aid in surface creation. |
| | 17 | | /// </summary> |
| | 18 | | public static class SurfaceFactory |
| | 19 | | { |
| | 20 | | /// <summary> |
| | 21 | | /// Gets or sets the ArrayPool used by image loader. |
| | 22 | | /// </summary> |
| 21 | 23 | | public static ArrayPool<byte> ArrayPool { get; set; } = ArrayPool<byte>.Shared; |
| | 24 | |
|
| | 25 | | /// <summary> |
| | 26 | | /// Creates a RGBA8888 surface by loading a file from the specified path. |
| | 27 | | /// </summary> |
| 4 | 28 | | public static Surface FromFile(string path) => FromImage(Image.Load(path)); |
| | 29 | |
|
| | 30 | | /// <summary> |
| | 31 | | /// Creates a RGBA8888 surface by loading a file from the specified stream. |
| | 32 | | /// </summary> |
| | 33 | | public static Surface FromStream(Stream stream, IImageDecoder decoder) => |
| 6 | 34 | | FromImage(Image.Load(stream, decoder)); |
| | 35 | |
|
| | 36 | | /// <summary> |
| | 37 | | /// Creates a RGBA8888 surface from the specified Image object. |
| | 38 | | /// </summary> |
| | 39 | | public static Surface FromImage<TPixel>(Image<TPixel> image) |
| | 40 | | where TPixel : struct, IPixel<TPixel> |
| | 41 | | { |
| 10 | 42 | | var cloned = image.CloneAs<Rgba32>(); |
| 10 | 43 | | var pixels = cloned.GetPixelSpan(); |
| 10 | 44 | | var bytes = ArrayPool.Rent(pixels.Length * 4); |
| 90220 | 45 | | for (int i = 0; i < pixels.Length; i++) |
| | 46 | | { |
| 45100 | 47 | | var pixel = pixels[i]; |
| 45100 | 48 | | bytes[i * 4] = pixel.A; |
| 45100 | 49 | | bytes[i * 4 + 1] = pixel.B; |
| 45100 | 50 | | bytes[i * 4 + 2] = pixel.G; |
| 45100 | 51 | | bytes[i * 4 + 3] = pixel.R; |
| | 52 | | } |
| 0 | 53 | | var surface = Surface.CreateFrom(bytes, |
| 0 | 54 | | cloned.Width, |
| 0 | 55 | | cloned.Height, |
| 0 | 56 | | PixelFormat.Format_RGBA8888); |
| 10 | 57 | | ArrayPool.Return(bytes); |
| 10 | 58 | | return surface; |
| | 59 | | } |
| | 60 | | } |
| | 61 | | } |