| | 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 TextureFactory |
| | 19 | | { |
| | 20 | | /// <summary> |
| | 21 | | /// Gets or sets the ArrayPool used by image loader. |
| | 22 | | /// </summary> |
| 27 | 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> |
| | 28 | | public static Texture FromFile(Graphics graphics, TextureScalingQuality quality, |
| | 29 | | string path) => |
| 0 | 30 | | FromImage(graphics, quality, Image.Load(path)); |
| | 31 | |
|
| | 32 | | /// <summary> |
| | 33 | | /// Creates a RGBA8888 surface by loading a file from the specified stream. |
| | 34 | | /// </summary> |
| | 35 | | public static Texture FromStream(Graphics graphics, Stream stream, |
| | 36 | | TextureScalingQuality quality, |
| | 37 | | IImageDecoder decoder) => |
| 1 | 38 | | FromImage(graphics, quality, Image.Load(stream, decoder)); |
| | 39 | |
|
| | 40 | | /// <summary> |
| | 41 | | /// Creates a RGBA8888 surface from the specified Image object. |
| | 42 | | /// </summary> |
| | 43 | | public static Texture FromImage<TPixel>(Graphics graphics, |
| | 44 | | TextureScalingQuality quality, Image<TPixel> image) |
| | 45 | | where TPixel : struct, IPixel<TPixel> |
| | 46 | | { |
| 13 | 47 | | var cloned = image.CloneAs<Rgba32>(); |
| 13 | 48 | | var pixels = cloned.GetPixelSpan(); |
| 13 | 49 | | var bytes = ArrayPool.Rent(pixels.Length * 4); |
| 182058 | 50 | | for (int i = 0; i < pixels.Length; i++) |
| | 51 | | { |
| 91016 | 52 | | var pixel = pixels[i]; |
| 91016 | 53 | | bytes[i * 4] = pixel.A; |
| 91016 | 54 | | bytes[i * 4 + 1] = pixel.B; |
| 91016 | 55 | | bytes[i * 4 + 2] = pixel.G; |
| 91016 | 56 | | bytes[i * 4 + 3] = pixel.R; |
| | 57 | | } |
| 0 | 58 | | var texture = graphics.CreateTexture(cloned.Width, cloned.Height, |
| 0 | 59 | | quality, PixelFormat.Format_RGBA8888); |
| 13 | 60 | | texture.SetPixels(ref bytes); |
| 13 | 61 | | ArrayPool.Return(bytes); |
| 13 | 62 | | return texture; |
| | 63 | | } |
| | 64 | | } |
| | 65 | | } |