-
Notifications
You must be signed in to change notification settings - Fork 0
/
SharpImage.cs
435 lines (383 loc) · 16 KB
/
SharpImage.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
using IS4.SFI.Formats;
using IS4.SFI.Services;
using IS4.SFI.Tools.IO;
using Microsoft.CSharp.RuntimeBinder;
using SixLabors.ImageSharp;
using SixLabors.ImageSharp.Advanced;
using SixLabors.ImageSharp.Formats;
using SixLabors.ImageSharp.Formats.Png;
using SixLabors.ImageSharp.Metadata;
using SixLabors.ImageSharp.PixelFormats;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.IO;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using Color = System.Drawing.Color;
using IImage = SixLabors.ImageSharp.IImage;
namespace IS4.SFI.Tools.Images
{
/// <summary>
/// Provides an <see cref="IImage{TUnderlying}"/> implementation
/// backed by an instance of <see cref="IImage"/>.
/// </summary>
public class SharpImage : ImageBase<IImage>
{
Image Image => UnderlyingImage as Image ?? throw new NotSupportedException();
ImageMetadata ImageMetadata => UnderlyingImage.Metadata;
PixelTypeInfo PixelType => UnderlyingImage.PixelType;
/// <inheritdoc/>
public SharpImage(IImage underlyingImage, IFileFormat<IImage> format) : base(underlyingImage, format)
{
}
/// <inheritdoc/>
public override int Width => UnderlyingImage.Width;
/// <inheritdoc/>
public override int Height => UnderlyingImage.Height;
/// <inheritdoc/>
public override double HorizontalResolution => ResolutionUnit * ImageMetadata.HorizontalResolution;
/// <inheritdoc/>
public override double VerticalResolution => ResolutionUnit * ImageMetadata.VerticalResolution;
/// <summary>
/// The coefficient to use when converting resolution to pixel per inch.
/// </summary>
private double ResolutionUnit{
get{
switch(ImageMetadata.ResolutionUnits)
{
case PixelResolutionUnit.AspectRatio:
return 96;
case PixelResolutionUnit.PixelsPerInch:
return 1;
case PixelResolutionUnit.PixelsPerCentimeter:
return 2.54d;
case PixelResolutionUnit.PixelsPerMeter:
return 0.0254d;
default:
throw new NotSupportedException();
}
}
}
/// <inheritdoc/>
public override bool HasAlpha => PixelType.AlphaRepresentation is not (null or 0);
/// <inheritdoc/>
public override int BitDepth{
get{
if(ImageMetadata.GetPngMetadata() is { BitDepth: { } pngBits and not 0 } png)
{
if(png.ColorType is PngColorType.Rgb or PngColorType.RgbWithAlpha)
{
return PixelType.BitsPerPixel;
}
return (int)pngBits;
}
if(ImageMetadata.GetGifMetadata() is { GlobalColorTableLength: var palSize and > 0 })
{
return (int)Math.Ceiling(Math.Log(palSize / 3, 2));
}
if(ImageMetadata.GetBmpMetadata() is { InfoHeaderType: not 0, BitsPerPixel: var bmpBits and > 0 })
{
return (int)bmpBits;
}
return PixelType.BitsPerPixel;
}
}
static readonly Type pixelType32bppArgb = typeof(Bgra32);
/// <inheritdoc/>
public override bool Is32bppArgb {
[DynamicDependency(nameof(GetImagePixelType), typeof(SharpImage))]
get{
try{
return pixelType32bppArgb.Equals(GetImagePixelType((dynamic)UnderlyingImage));
}catch(RuntimeBinderException)
{
return false;
}
}
}
/// <inheritdoc/>
public override IReadOnlyList<Color> Palette => Array.Empty<Color>();
/// <inheritdoc/>
public override int? PaletteSize{
get{
if(ImageMetadata.GetPngMetadata() is { BitDepth: { } pngBits and not 0 } png)
{
switch(png.ColorType)
{
case PngColorType.Palette:
case PngColorType.Grayscale:
case PngColorType.GrayscaleWithAlpha:
return (int)pngBits <= 8 ? (1 << (int)pngBits) : 0;
case PngColorType.Rgb:
case PngColorType.RgbWithAlpha:
return 0;
default:
return null;
}
}
if(ImageMetadata.GetGifMetadata() is { GlobalColorTableLength: var fromGif and > 0 })
{
return fromGif / 3;
}
if(ImageMetadata.GetBmpMetadata() is { BitsPerPixel: var bmpBits and > 0 })
{
return (int)bmpBits <= 8 ? (1 << (int)bmpBits) : 0;
}
if(ImageMetadata.GetJpegMetadata() != null)
{
return 0;
}
return null;
}
}
/// <inheritdoc/>
public override IReadOnlyList<KeyValuePair<object, object>> Metadata => UnderlyingImage.GetMetadata();
/// <inheritdoc/>
public override IReadOnlyList<KeyValuePair<long, ReadOnlyMemory<byte>>> RawMetadata => UnderlyingImage.GetRawMetadata();
/// <summary>
/// Retrieves the pixel type of an image, as a type implementing <see cref="IPixel{TSelf}"/>.
/// </summary>
/// <typeparam name="TPixel">The pixel type of the image.</typeparam>
/// <returns>The pixel type of an image.</returns>
protected static Type GetImagePixelType<TPixel>(Image<TPixel> image) where TPixel : unmanaged, IPixel<TPixel>
{
return typeof(TPixel);
}
/// <inheritdoc/>
[DynamicDependency(nameof(GetImagePixel), typeof(SharpImage))]
public override Color GetPixel(int x, int y)
{
try{
return GetImagePixel((dynamic)UnderlyingImage, x, y);
}catch(RuntimeBinderException)
{
throw new NotSupportedException();
}
}
/// <inheritdoc/>
[DynamicDependency(nameof(SetImagePixel), typeof(SharpImage))]
public override void SetPixel(int x, int y, Color color)
{
try{
SetImagePixel((dynamic)UnderlyingImage, x, y, color);
}catch(RuntimeBinderException)
{
throw new NotSupportedException();
}
}
/// <summary>
/// Retrieves the color value of a particular pixel in an image.
/// </summary>
/// <typeparam name="TPixel">The pixel type of the image.</typeparam>
/// <param name="image">The image to access.</param>
/// <param name="x">The X coordinate of the pixel.</param>
/// <param name="y">The Y coordinate of the pixel.</param>
/// <returns>The color of the pixel at the specified coordinates.</returns>
protected static Color GetImagePixel<TPixel>(Image<TPixel> image, int x, int y) where TPixel : unmanaged, IPixel<TPixel>
{
Rgba32 pixel = default;
image[x, y].ToRgba32(ref pixel);
return Color.FromArgb(pixel.A, pixel.R, pixel.G, pixel.B);
}
/// <summary>
/// Assigns the color value of a particular pixel in an image.
/// </summary>
/// <typeparam name="TPixel">The pixel type of the image.</typeparam>
/// <param name="image">The image to access.</param>
/// <param name="x">The X coordinate of the pixel.</param>
/// <param name="y">The Y coordinate of the pixel.</param>
/// <param name="color">The color to assign at the specified coordinates.</param>
protected static void SetImagePixel<TPixel>(Image<TPixel> image, int x, int y, Color color) where TPixel : unmanaged, IPixel<TPixel>
{
TPixel pixel = default;
pixel.FromRgba32(new(color.R, color.G, color.B, color.A));
image[x, y] = pixel;
}
/// <inheritdoc/>
[DynamicDependency(nameof(GetImageData), typeof(SharpImage))]
public override IImageData GetData()
{
try{
return GetImageData((dynamic)UnderlyingImage);
}catch(RuntimeBinderException)
{
throw new NotSupportedException();
}
}
/// <summary>
/// Obtains the raw pixel data of the image.
/// </summary>
/// <typeparam name="TPixel">The pixel type of the image.</typeparam>
/// <param name="image">The image to access.</param>
/// <returns>An instance of <see cref="IImageData"/> for the image pixels.</returns>
protected IImageData GetImageData<TPixel>(Image<TPixel> image) where TPixel : unmanaged, IPixel<TPixel>
{
return new SharpImageData<TPixel>(this, image);
}
/// <inheritdoc/>
public override Services.IImage? GetThumbnail()
{
var thumbnail = ImageMetadata.ExifProfile?.CreateThumbnail();
if(thumbnail == null)
{
return null;
}
return new SharpImage(thumbnail, UnderlyingFormat);
}
/// <inheritdoc/>
public override void Save(Stream output, string mediaType)
{
var manager = Configuration.Default.ImageFormatsManager;
var format = manager.FindFormatByMimeType(mediaType) ?? throw new ArgumentException("The specified format cannot be found.", nameof(mediaType));
var encoder = manager.FindEncoder(format) ?? throw new ArgumentException("The specified format's encoder cannot be found.", nameof(mediaType));
Image.Save(output, encoder);
}
/// <inheritdoc/>
public override Services.IImage Resize(int newWidth, int newHeight, bool preserveResolution, bool use32bppArgb, Color backgroundColor)
{
var resized = Image.Resize(newWidth, newHeight, use32bppArgb, backgroundColor, preserveResolution);
return new SharpImage(resized, UnderlyingFormat);
}
public override void ResizeInPlace(int newWidth, int newHeight, bool preserveResolution, Color backgroundColor)
{
Image.ResizeInPlace(newWidth, newHeight, backgroundColor, preserveResolution);
}
public override Services.IImage RotateFlip(int clockwise90DegreeTurns, bool flipHorizontal, bool flipVertical, bool use32bppArgb)
{
var rotated = Image.RotateFlip(clockwise90DegreeTurns, flipHorizontal, flipVertical, use32bppArgb);
return new SharpImage(rotated, UnderlyingFormat);
}
public override void RotateFlipInPlace(int clockwise90DegreeTurns, bool flipHorizontal, bool flipVertical)
{
Image.RotateFlipInPlace(clockwise90DegreeTurns, flipHorizontal, flipVertical);
}
public override ImageBase<IImage> Clone(bool use32bppArgb)
{
return new SharpImage(Image.Clone(use32bppArgb), UnderlyingFormat);
}
}
/// <summary>
/// Provides an <see cref="IImage{TUnderlying}"/> implementation
/// backed by an instance of <see cref="Image{TPixel}"/>.
/// </summary>
/// <typeparam name="TPixel">The pixel type of the image.</typeparam>
public class SharpImage<TPixel> : SharpImage where TPixel : unmanaged, IPixel<TPixel>
{
Image<TPixel> Image => UnderlyingImage as Image<TPixel> ?? throw new InvalidOperationException();
/// <inheritdoc/>
public SharpImage(Image<TPixel> underlyingImage, IFileFormat<IImage> format) : base(underlyingImage, format)
{
}
/// <inheritdoc/>
public override Color GetPixel(int x, int y)
{
return GetImagePixel(Image, x, y);
}
/// <inheritdoc/>
public override void SetPixel(int x, int y, Color color)
{
SetImagePixel(Image, x, y, color);
}
/// <inheritdoc/>
public override IImageData GetData()
{
return GetImageData(Image);
}
}
/// <summary>
/// Provides an <see cref="IImageData"/> implementation
/// backed by an instance of <see cref="Image{TPixel}"/>.
/// </summary>
/// <typeparam name="TPixel">The pixel type of the image.</typeparam>
public class SharpImageData<TPixel> : MemoryImageData<IImage> where TPixel : unmanaged, IPixel<TPixel>
{
readonly Image<TPixel> data;
/// <inheritdoc/>
public override bool IsContiguous { get; }
/// <summary>
/// Creates a new instance of the data.
/// </summary>
/// <param name="image">The value of <see cref="ImageData{TUnderlying}.Image"/>.</param>
/// <param name="data">The instance of <see cref="Image{TPixel}"/> to access the data of.</param>
public SharpImageData(SharpImage image, Image<TPixel> data) : base(image, data.Width * Unsafe.SizeOf<TPixel>(), data.PixelType.BitsPerPixel)
{
this.data = data;
// On contiguous buffers, the base implementation of GetPixel and GetRow is better since there is no MemoryManager allocation
IsContiguous = data.DangerousTryGetSinglePixelMemory(out _);
}
/// <inheritdoc/>
public override Span<byte> this[int x, int y] {
get {
if(IsContiguous)
{
return base[x, y];
}
var memory = data.DangerousGetPixelRowMemory(y).Slice(x, 1);
return MemoryMarshal.Cast<TPixel, byte>(memory.Span);
}
}
/// <inheritdoc/>
public override Span<byte> this[int y] {
get {
if(IsContiguous)
{
return base[y];
}
var memory = data.DangerousGetPixelRowMemory(y);
return MemoryMarshal.Cast<TPixel, byte>(memory.Span);
}
}
/// <inheritdoc/>
public override Memory<byte> GetPixel(int x, int y)
{
if(IsContiguous)
{
return base.GetPixel(x, y);
}
var memory = data.DangerousGetPixelRowMemory(y).Slice(x, 1);
return MemoryUtils.Cast<TPixel, byte>(memory);
}
/// <inheritdoc/>
public override Memory<byte> GetRow(int y)
{
if(IsContiguous)
{
return base.GetRow(y);
}
var memory = data.DangerousGetPixelRowMemory(y);
return MemoryUtils.Cast<TPixel, byte>(memory);
}
/// <inheritdoc/>
public override Span<byte> GetSpan()
{
if(!data.DangerousTryGetSinglePixelMemory(out var memory))
{
throw new NotSupportedException("The bitmap's memory is not contiguous.");
}
return MemoryMarshal.Cast<TPixel, byte>(memory.Span);
}
/// <inheritdoc/>
protected override void Dispose(bool disposing)
{
}
/// <inheritdoc/>
protected override Stream Open()
{
return new DataStream(data);
}
class DataStream : BitmapRowDataStream
{
readonly Image<TPixel> data;
public DataStream(Image<TPixel> data) : base(data.Height, data.Width * Unsafe.SizeOf<TPixel>())
{
this.data = data;
}
protected override void CopyData(int row, int offset, ArraySegment<byte> target)
{
var rowData = MemoryMarshal.Cast<TPixel, byte>(data.DangerousGetPixelRowMemory(row).Span).Slice(offset);
rowData.CopyTo(target.AsSpan());
}
}
}
}