| | | 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 Graphics-related extensions. |
| | | 13 | | /// </summary> |
| | | 14 | | public static class GraphicsExtensions |
| | | 15 | | { |
| | | 16 | | /// <summary> |
| | | 17 | | /// Saves the graphics to the specified stream. |
| | | 18 | | /// </summary> |
| | | 19 | | public static void SaveAsPng(this Graphics graphics, Stream stream) => |
| | 12 | 20 | | graphics.Save(image => image.SaveAsPng(stream)); |
| | | 21 | | |
| | | 22 | | /// <summary> |
| | | 23 | | /// Saves the graphics to the specified file, overwriting it if it exists. |
| | | 24 | | /// </summary> |
| | | 25 | | public static void SaveAsPng(this Graphics graphics, string path) |
| | | 26 | | { |
| | 0 | 27 | | using (var stream = new FileStream(path, FileMode.Create)) |
| | 0 | 28 | | graphics.SaveAsPng(stream); |
| | 0 | 29 | | } |
| | | 30 | | |
| | | 31 | | /// <summary> |
| | | 32 | | /// Saves the graphics using the specified save action. |
| | | 33 | | /// </summary> |
| | | 34 | | /// <example> |
| | | 35 | | /// graphics.Save(image => image.SaveAsJpeg("file.jpg")) |
| | | 36 | | /// </example> |
| | | 37 | | public static void Save(this Graphics graphics, |
| | | 38 | | Action<Image<Rgba32>> onSave) |
| | | 39 | | { |
| | 6 | 40 | | var targetFormat = PixelFormat.Format_ABGR8888; |
| | 6 | 41 | | var size = graphics.OutputSize; |
| | 6 | 42 | | var pixelData = new ColorRGB888[graphics.PixelCount]; |
| | 6 | 43 | | graphics.ReadPixels(ref pixelData); |
| | 6 | 44 | | var pixelHandle = GCHandle.Alloc(pixelData, GCHandleType.Pinned); |
| | | 45 | | try |
| | | 46 | | { |
| | 6 | 47 | | var image = new Image<Rgba32>(size.Width, size.Height); |
| | | 48 | | unsafe |
| | 6 | 49 | | { |
| | 6 | 50 | | fixed (void* target = &MemoryMarshal.GetReference(image.GetPixelSpan())) |
| | | 51 | | { |
| | 0 | 52 | | Pixels.Convert(size.Width, size.Height, |
| | 0 | 53 | | 4 * size.Width, 4 * size.Width, |
| | 0 | 54 | | PixelFormat.Format_RGB888, |
| | 0 | 55 | | targetFormat, |
| | 0 | 56 | | pixelHandle.AddrOfPinnedObject(), |
| | 0 | 57 | | (IntPtr)target); |
| | | 58 | | } |
| | | 59 | | } |
| | 6 | 60 | | onSave(image); |
| | 6 | 61 | | image.Dispose(); |
| | 6 | 62 | | } |
| | | 63 | | finally |
| | | 64 | | { |
| | 6 | 65 | | pixelHandle.Free(); |
| | 6 | 66 | | } |
| | 6 | 67 | | } |
| | | 68 | | } |
| | | 69 | | } |