/
Bitmap.cs
512 lines (436 loc) · 17.2 KB
/
Bitmap.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
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System.ComponentModel;
using System.Drawing.Imaging;
#if NET9_0_OR_GREATER
using System.Drawing.Imaging.Effects;
using System.Runtime.Versioning;
#endif
using System.IO;
using System.Runtime.CompilerServices;
using System.Runtime.Serialization;
namespace System.Drawing;
[Editor($"System.Drawing.Design.BitmapEditor, {AssemblyRef.SystemDrawingDesign}",
$"System.Drawing.Design.UITypeEditor, {AssemblyRef.SystemDrawing}")]
[Serializable]
[TypeForwardedFrom(AssemblyRef.SystemDrawing)]
public sealed unsafe class Bitmap : Image, IPointer<GpBitmap>
{
private static readonly Color s_defaultTransparentColor = Color.LightGray;
private Bitmap() { }
internal Bitmap(GpBitmap* ptr) => SetNativeImage((GpImage*)ptr);
public Bitmap(string filename) : this(filename, useIcm: false) { }
public Bitmap(string filename, bool useIcm)
{
// GDI+ will read this file multiple times. Get the fully qualified path
// so if the app's default directory changes we won't get an error.
filename = Path.GetFullPath(filename);
GpBitmap* bitmap;
fixed (char* fn = filename)
{
Status status = useIcm
? PInvoke.GdipCreateBitmapFromFileICM(fn, &bitmap)
: PInvoke.GdipCreateBitmapFromFile(fn, &bitmap);
status.ThrowIfFailed();
}
ValidateImage((GpImage*)bitmap);
SetNativeImage((GpImage*)bitmap);
GetAnimatedGifRawData(this, filename, dataStream: null);
}
public Bitmap(Stream stream) : this(stream, false)
{
}
public Bitmap(Stream stream, bool useIcm)
{
ArgumentNullException.ThrowIfNull(stream);
using var iStream = stream.ToIStream(makeSeekable: true);
GpBitmap* bitmap = null;
Status status = useIcm
? PInvoke.GdipCreateBitmapFromStreamICM(iStream, &bitmap)
: PInvoke.GdipCreateBitmapFromStream(iStream, &bitmap);
status.ThrowIfFailed();
ValidateImage((GpImage*)bitmap);
SetNativeImage((GpImage*)bitmap);
GetAnimatedGifRawData(this, filename: null, stream);
}
public Bitmap(Type type, string resource) : this(GetResourceStream(type, resource))
{
}
private static Stream GetResourceStream(Type type, string resource)
{
ArgumentNullException.ThrowIfNull(type);
ArgumentNullException.ThrowIfNull(resource);
return type.Module.Assembly.GetManifestResourceStream(type, resource)
?? throw new ArgumentException(SR.Format(SR.ResourceNotFound, type, resource));
}
public Bitmap(int width, int height) : this(width, height, PixelFormat.Format32bppArgb)
{
}
public Bitmap(int width, int height, Graphics g)
{
ArgumentNullException.ThrowIfNull(g);
GpBitmap* bitmap;
PInvoke.GdipCreateBitmapFromGraphics(width, height, g.NativeGraphics, &bitmap).ThrowIfFailed();
SetNativeImage((GpImage*)bitmap);
GC.KeepAlive(g);
}
public Bitmap(int width, int height, int stride, PixelFormat format, IntPtr scan0)
{
GpBitmap* bitmap;
PInvoke.GdipCreateBitmapFromScan0(width, height, stride, (int)format, (byte*)scan0, &bitmap).ThrowIfFailed();
SetNativeImage((GpImage*)bitmap);
}
public Bitmap(int width, int height, PixelFormat format)
{
GpBitmap* bitmap;
PInvoke.GdipCreateBitmapFromScan0(width, height, 0, (int)format, null, &bitmap).ThrowIfFailed();
SetNativeImage((GpImage*)bitmap);
}
public Bitmap(Image original) : this(original, original.Width, original.Height)
{
}
public Bitmap(Image original, Size newSize) : this(original, newSize.Width, newSize.Height)
{
}
public Bitmap(Image original, int width, int height) : this(width, height, PixelFormat.Format32bppArgb)
{
ArgumentNullException.ThrowIfNull(original);
using var g = Graphics.FromImage(this);
g.Clear(Color.Transparent);
g.DrawImage(original, 0, 0, width, height);
}
private Bitmap(SerializationInfo info, StreamingContext context) : base(info, context)
{
}
GpBitmap* IPointer<GpBitmap>.Pointer => (GpBitmap*)((Image)this).Pointer();
public static Bitmap FromHicon(IntPtr hicon)
{
GpBitmap* bitmap;
PInvoke.GdipCreateBitmapFromHICON((HICON)hicon, &bitmap).ThrowIfFailed();
return new Bitmap(bitmap);
}
public static Bitmap FromResource(IntPtr hinstance, string bitmapName)
{
ArgumentNullException.ThrowIfNull(bitmapName);
GpBitmap* bitmap = null;
fixed (char* bn = bitmapName)
{
PInvoke.GdipCreateBitmapFromResource((HINSTANCE)hinstance, bn, &bitmap).ThrowIfFailed();
}
return new Bitmap(bitmap);
}
[EditorBrowsable(EditorBrowsableState.Advanced)]
public IntPtr GetHbitmap() => GetHbitmap(Color.LightGray);
[EditorBrowsable(EditorBrowsableState.Advanced)]
public IntPtr GetHbitmap(Color background)
{
HBITMAP hbitmap;
Status status = PInvoke.GdipCreateHBITMAPFromBitmap(
this.Pointer(),
&hbitmap,
(uint)ColorTranslator.ToWin32(background));
if (status == Status.InvalidParameter && (Width >= short.MaxValue || Height >= short.MaxValue))
{
throw new ArgumentException(SR.GdiplusInvalidSize);
}
status.ThrowIfFailed();
GC.KeepAlive(this);
return hbitmap;
}
[EditorBrowsable(EditorBrowsableState.Advanced)]
public IntPtr GetHicon()
{
HICON hicon;
PInvoke.GdipCreateHICONFromBitmap(this.Pointer(), &hicon).ThrowIfFailed();
GC.KeepAlive(this);
return hicon;
}
public Bitmap Clone(RectangleF rect, PixelFormat format)
{
if (rect.Width == 0 || rect.Height == 0)
{
throw new ArgumentException(SR.Format(SR.GdiplusInvalidRectangle, rect.ToString()));
}
GpBitmap* clone;
Status status = PInvoke.GdipCloneBitmapArea(
rect.X, rect.Y, rect.Width, rect.Height,
(int)format,
this.Pointer(),
&clone);
if (status != Status.Ok || clone is null)
{
throw Gdip.StatusException(status);
}
GC.KeepAlive(this);
return new Bitmap(clone);
}
public void MakeTransparent()
{
Color transparent = s_defaultTransparentColor;
if (Height > 0 && Width > 0)
{
transparent = GetPixel(0, Size.Height - 1);
}
if (transparent.A < 255)
{
// It's already transparent, and if we proceeded, we will do something
// unintended like making black transparent
return;
}
MakeTransparent(transparent);
}
public void MakeTransparent(Color transparentColor)
{
if (RawFormat.Guid == ImageFormat.Icon.Guid)
{
throw new InvalidOperationException(SR.CantMakeIconTransparent);
}
Size size = Size;
// The new bitmap must be in 32bppARGB format, because that's the only
// thing that supports alpha. (And that's what the image is initialized to -- transparent)
using Bitmap result = new(size.Width, size.Height, PixelFormat.Format32bppArgb);
using var graphics = Graphics.FromImage(result);
graphics.Clear(Color.Transparent);
Rectangle rectangle = new(0, 0, size.Width, size.Height);
using (ImageAttributes attributes = new())
{
attributes.SetColorKey(transparentColor, transparentColor);
graphics.DrawImage(
this,
rectangle,
0, 0, size.Width, size.Height,
GraphicsUnit.Pixel,
attributes,
callback: null,
callbackData: 0);
}
// Swap nativeImage pointers to make it look like we modified the image in place
GpBitmap* temp = this.Pointer();
SetNativeImage((GpImage*)result.Pointer());
result.SetNativeImage((GpImage*)temp);
}
public BitmapData LockBits(Rectangle rect, ImageLockMode flags, PixelFormat format) =>
LockBits(rect, flags, format, new());
public BitmapData LockBits(Rectangle rect, ImageLockMode flags, PixelFormat format, BitmapData bitmapData)
{
ArgumentNullException.ThrowIfNull(bitmapData);
fixed (void* data = &bitmapData.GetPinnableReference())
{
this.LockBits(
rect,
(GdiPlus.ImageLockMode)flags,
(GdiPlus.PixelFormat)format,
ref Unsafe.AsRef<GdiPlus.BitmapData>(data));
}
GC.KeepAlive(this);
return bitmapData;
}
public void UnlockBits(BitmapData bitmapdata)
{
ArgumentNullException.ThrowIfNull(bitmapdata);
fixed (void* data = &bitmapdata.GetPinnableReference())
{
this.UnlockBits(ref Unsafe.AsRef<GdiPlus.BitmapData>(data));
}
GC.KeepAlive(this);
}
public Color GetPixel(int x, int y)
{
if (x < 0 || x >= Width)
{
throw new ArgumentOutOfRangeException(nameof(x), SR.ValidRangeX);
}
if (y < 0 || y >= Height)
{
throw new ArgumentOutOfRangeException(nameof(y), SR.ValidRangeY);
}
uint color;
PInvoke.GdipBitmapGetPixel(this.Pointer(), x, y, &color).ThrowIfFailed();
GC.KeepAlive(this);
return Color.FromArgb((int)color);
}
public void SetPixel(int x, int y, Color color)
{
if ((PixelFormat & PixelFormat.Indexed) != 0)
{
throw new InvalidOperationException(SR.GdiplusCannotSetPixelFromIndexedPixelFormat);
}
if (x < 0 || x >= Width)
{
throw new ArgumentOutOfRangeException(nameof(x), SR.ValidRangeX);
}
if (y < 0 || y >= Height)
{
throw new ArgumentOutOfRangeException(nameof(y), SR.ValidRangeY);
}
PInvoke.GdipBitmapSetPixel(this.Pointer(), x, y, (uint)color.ToArgb()).ThrowIfFailed();
GC.KeepAlive(this);
}
public void SetResolution(float xDpi, float yDpi)
{
PInvoke.GdipBitmapSetResolution(this.Pointer(), xDpi, yDpi).ThrowIfFailed();
GC.KeepAlive(this);
}
public Bitmap Clone(Rectangle rect, PixelFormat format)
{
if (rect.Width == 0 || rect.Height == 0)
{
throw new ArgumentException(SR.Format(SR.GdiplusInvalidRectangle, rect.ToString()));
}
GpBitmap* clone;
Status status = PInvoke.GdipCloneBitmapAreaI(
rect.X, rect.Y, rect.Width, rect.Height,
(int)format,
this.Pointer(),
&clone);
if (status != Status.Ok || clone is null)
{
throw Gdip.StatusException(status);
}
GC.KeepAlive(this);
return new Bitmap(clone);
}
#if NET9_0_OR_GREATER
/// <summary>
/// Alters the bitmap by applying the given <paramref name="effect"/>.
/// </summary>
/// <param name="effect">The effect to apply.</param>
/// <param name="area">The area to apply to, or <see cref="Rectangle.Empty"/> for the entire image.</param>
public void ApplyEffect(Effect effect, Rectangle area = default)
{
RECT rect = area;
PInvoke.GdipBitmapApplyEffect(
this.Pointer(),
effect.Pointer(),
area.IsEmpty ? null : &rect,
useAuxData: false,
auxData: null,
auxDataSize: null).ThrowIfFailed();
GC.KeepAlive(this);
GC.KeepAlive(effect);
}
/// <summary>
/// Converts the bitmap to the specified <paramref name="format"/> using the given <paramref name="ditherType"/>.
/// The original pixel data is replaced with the new format.
/// </summary>
/// <param name="format">
/// <para>
/// The new pixel format. <see cref="PixelFormat.Format16bppGrayScale"/> is not supported.
/// </para>
/// </param>
/// <param name="ditherType">
/// <para>
/// The dithering algorithm. Pass <see cref="DitherType.None"/> when the conversion does not reduce the bit depth
/// of the pixel data.
/// </para>
/// <para>
/// This must be <see cref="DitherType.Solid"/> or <see cref="DitherType.ErrorDiffusion"/> if the <paramref name="paletteType"/>
/// is <see cref="PaletteType.Custom"/> or <see cref="PaletteType.FixedBW"/>.
/// </para>
/// </param>
/// <param name="paletteType">
/// <para>
/// The palette type to use when the pixel format is indexed. Ignored for non-indexed pixel formats.
/// </para>
/// </param>
/// <param name="palette">
/// <para>
/// Pointer to a <see cref="ColorPalette"/> that specifies the palette whose indexes are stored in the pixel data
/// of the converted bitmap. This must be specified for indexed pixel formats.
/// </para>
/// <para>
/// This palette (called the actual palette) does not have to have the type specified by
/// the <paramref name="paletteType"/> parameter. The <paramref name="paletteType"/> parameter specifies a standard
/// palette that can be used by any of the ordered or spiral dithering algorithms. If the actual palette has a type
/// other than that specified by the <paramref name="paletteType"/> parameter, then
/// <see cref="ConvertFormat(PixelFormat, DitherType, PaletteType, ColorPalette?, float)"/> performs a nearest-color
/// conversion from the standard palette to the actual palette.
/// </para>
/// </param>
/// <param name="alphaThresholdPercent">
/// <para>
/// Real number in the range 0 through 100 that specifies which pixels in the source bitmap will map to the
/// transparent color in the converted bitmap.
/// </para>
/// <para>
/// A value of 0 specifies that none of the source pixels map to the transparent color. A value of 100
/// specifies that any pixel that is not fully opaque will map to the transparent color. A value of t specifies
/// that any source pixel less than t percent of fully opaque will map to the transparent color. Note that for
/// the alpha threshold to be effective, the palette must have a transparent color. If the palette does not have
/// a transparent color, pixels with alpha values below the threshold will map to color that most closely
/// matches (0, 0, 0, 0), usually black.
/// </para>
/// </param>
/// <remarks>
/// <para>
/// <paramref name="paletteType"/> and <paramref name="palette"/> really only have relevance with indexed pixel
/// formats. You can pass a <see cref="ColorPalette"/> for non-indexed pixel formats, but it has no impact on the
/// transformation and will effective just call <see cref="Image.Palette"/> to set the palette when the conversion
/// is complete.
/// </para>
/// </remarks>
[RequiresPreviewFeatures]
public void ConvertFormat(
PixelFormat format,
DitherType ditherType,
PaletteType paletteType = PaletteType.Custom,
ColorPalette? palette = null,
float alphaThresholdPercent = 0.0f)
{
if (palette is null)
{
PInvoke.GdipBitmapConvertFormat(
this.Pointer(),
(int)format,
(GdiPlus.DitherType)ditherType,
(GdiPlus.PaletteType)paletteType,
null,
alphaThresholdPercent).ThrowIfFailed();
}
else
{
using var buffer = palette.ConvertToBuffer();
fixed (void* b = buffer)
{
PInvoke.GdipBitmapConvertFormat(
this.Pointer(),
(int)format,
(GdiPlus.DitherType)ditherType,
(GdiPlus.PaletteType)paletteType,
(GdiPlus.ColorPalette*)b,
alphaThresholdPercent).ThrowIfFailed();
}
}
GC.KeepAlive(this);
}
/// <summary>
/// Converts the bitmap to the specified <paramref name="format"/>.
/// The original pixel data is replaced with the new format.
/// </summary>
/// <param name="format">
/// <para>
/// The new pixel format. <see cref="PixelFormat.Format16bppGrayScale"/> is not supported.
/// </para>
/// </param>
[RequiresPreviewFeatures]
public void ConvertFormat(PixelFormat format)
{
PixelFormat currentFormat = PixelFormat;
int targetSize = ((int)format >> 8) & 0xff;
int sourceSize = ((int)currentFormat >> 8) & 0xff;
if (!format.HasFlag(PixelFormat.Indexed))
{
ConvertFormat(format, targetSize > sourceSize ? DitherType.None : DitherType.Solid);
return;
}
int paletteSize = targetSize switch { 1 => 2, 4 => 16, _ => 256 };
bool hasAlpha = format.HasFlag(PixelFormat.Alpha);
if (hasAlpha)
{
paletteSize++;
}
ColorPalette palette = ColorPalette.CreateOptimalPalette(paletteSize, hasAlpha, this);
ConvertFormat(format, DitherType.ErrorDiffusion, PaletteType.Custom, palette, .25f);
}
#endif
}