/
IconConverter.cs
64 lines (58 loc) · 2.15 KB
/
IconConverter.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
// 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.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.IO;
namespace System.Drawing
{
public class IconConverter : ExpandableObjectConverter
{
public override bool CanConvertFrom(ITypeDescriptorContext? context, Type sourceType)
{
return (sourceType == typeof(byte[]));
}
public override bool CanConvertTo(ITypeDescriptorContext? context, [NotNullWhen(true)] Type? destinationType)
{
return destinationType == typeof(byte[]) || destinationType == typeof(string)
|| destinationType == typeof(Image) || destinationType == typeof(Bitmap);
}
public override object? ConvertFrom(ITypeDescriptorContext? context, CultureInfo? culture, object value)
{
return value is byte[] bytes ? new Icon(new MemoryStream(bytes)) : base.ConvertFrom(context, culture, value);
}
public override object? ConvertTo(ITypeDescriptorContext? context, CultureInfo? culture, object? value, Type destinationType)
{
if (destinationType == typeof(string))
{
if (value == null)
{
return SR.none;
}
else if (value is Icon)
{
return value.ToString()!;
}
}
else if (destinationType == typeof(byte[]))
{
if (value is Icon icon)
{
using (MemoryStream ms = new MemoryStream())
{
icon.Save(ms);
return ms.ToArray();
}
}
}
else if (destinationType == typeof(Image) || destinationType == typeof(Bitmap))
{
if (value is Icon icon)
{
return icon.ToBitmap();
}
}
throw GetConvertFromException(value);
}
}
}