/
ColorPalette.cs
96 lines (77 loc) · 2.33 KB
/
ColorPalette.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
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System.Runtime.InteropServices;
namespace System.Drawing.Imaging;
/// <summary>
/// Defines an array of colors that make up a color palette.
/// </summary>
public sealed class ColorPalette
{
// We don't provide a public constructor for ColorPalette because if we allow
// arbitrary creation of color palettes you could in theroy not only change the color entries, but the size
// of the palette and that is not valid for an image (meaning you cannot change the palette size for an image).
// ColorPalettes are only valid for "indexed" images like GIFs.
private int _flags;
private Color[] _entries;
/// <summary>
/// Specifies how to interpret the color information in the array of colors.
/// </summary>
public int Flags
{
get
{
return _flags;
}
}
/// <summary>
/// Specifies an array of <see cref='Color'/> objects.
/// </summary>
public Color[] Entries
{
get
{
return _entries;
}
}
internal ColorPalette(int count)
{
_entries = new Color[count];
}
internal ColorPalette()
{
_entries = new Color[1];
}
internal unsafe void ConvertFromMemory(IntPtr memory)
{
// Memory layout is:
// UINT Flags
// UINT Count
// ARGB Entries[size]
byte* pMemory = (byte*)memory;
_flags = *(int*)pMemory;
int size = *(int*)(pMemory + 4);
_entries = new Color[size];
for (int i = 0; i < size; i++)
{
int argb = *(int*)(pMemory + 8 + i * 4);
_entries[i] = Color.FromArgb(argb);
}
}
internal unsafe IntPtr ConvertToMemory()
{
// Memory layout is:
// UINT Flags
// UINT Count
// ARGB Entries[size]
int length = _entries.Length;
IntPtr memory = Marshal.AllocHGlobal(checked(4 * (2 + length)));
byte* pMemory = (byte*)memory;
*(int*)pMemory = _flags;
*(int*)(pMemory + 4) = length;
for (int i = 0; i < length; i++)
{
*(int*)(pMemory + 4 * (i + 2)) = _entries[i].ToArgb();
}
return memory;
}
}