| | 1 | | using System; |
| | 2 | | using System.IO; |
| | 3 | | using System.Runtime.InteropServices; |
| | 4 | | using Imagini.Drawing; |
| | 5 | | using SixLabors.ImageSharp; |
| | 6 | | using SixLabors.ImageSharp.Advanced; |
| | 7 | | using SixLabors.ImageSharp.PixelFormats; |
| | 8 | |
|
| | 9 | | namespace Imagini.ImageSharp |
| | 10 | | { |
| | 11 | | /// <summary> |
| | 12 | | /// Contains various Surface-related extensions. |
| | 13 | | /// </summary> |
| | 14 | | public static class SurfaceExtensions |
| | 15 | | { |
| | 16 | | /// <summary> |
| | 17 | | /// Saves the surface to the specified stream. |
| | 18 | | /// </summary> |
| | 19 | | public static void SaveAsPng(this Surface surface, Stream stream) => |
| 4 | 20 | | surface.Save(image => image.SaveAsPng(stream)); |
| | 21 | |
|
| | 22 | | /// <summary> |
| | 23 | | /// Saves the surface to the specified file, overwriting it if it exists. |
| | 24 | | /// </summary> |
| | 25 | | public static void SaveAsPng(this Surface surface, string path) |
| | 26 | | { |
| 1 | 27 | | using(var stream = new FileStream(path, FileMode.Create)) |
| 1 | 28 | | surface.SaveAsPng(stream); |
| 1 | 29 | | } |
| | 30 | |
|
| | 31 | | /// <summary> |
| | 32 | | /// Saves the surface using the specified save action. |
| | 33 | | /// </summary> |
| | 34 | | /// <example> |
| | 35 | | /// surface.Save(image => image.SaveAsJpeg("file.jpg")) |
| | 36 | | /// </example> |
| | 37 | | public static void Save(this Surface surface, |
| | 38 | | Action<Image<Rgba32>> onSave) |
| | 39 | | { |
| 2 | 40 | | var mustDispose = false; |
| 2 | 41 | | var source = surface; |
| 2 | 42 | | var targetFormat = PixelFormat.Format_ABGR8888; |
| 2 | 43 | | if (surface.PixelInfo.Format != targetFormat) |
| | 44 | | { |
| 2 | 45 | | source = surface.ConvertTo(targetFormat); |
| 2 | 46 | | mustDispose = true; |
| | 47 | | } |
| | 48 | |
|
| 2 | 49 | | var image = new Image<Rgba32>(surface.Width, surface.Height); |
| 2 | 50 | | unsafe { |
| 2 | 51 | | fixed(void* target = &MemoryMarshal.GetReference(image.GetPixelSpan())) |
| | 52 | | { |
| 0 | 53 | | Buffer.MemoryCopy( |
| 0 | 54 | | (void*)source.PixelsHandle, |
| 0 | 55 | | target, |
| 0 | 56 | | surface.SizeInBytes, surface.SizeInBytes); |
| | 57 | | } |
| | 58 | | } |
| 2 | 59 | | onSave(image); |
| | 60 | |
|
| 2 | 61 | | image.Dispose(); |
| 2 | 62 | | if (mustDispose) |
| 2 | 63 | | source.Dispose(); |
| 2 | 64 | | } |
| | 65 | | } |
| | 66 | | } |