forked from Nominom/BCnEncoder.NET
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathImageFile.cs
More file actions
76 lines (63 loc) · 1.64 KB
/
Copy pathImageFile.cs
File metadata and controls
76 lines (63 loc) · 1.64 KB
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
using System.IO;
using System.Linq;
using System.Text;
namespace BCnEncoder.Shared.ImageFiles
{
/// <summary>
/// The format identifier of an image file.
/// </summary>
public enum ImageFileFormat
{
/// <summary>
/// Represents the KTX image file format.
/// </summary>
Ktx,
/// <summary>
/// Represents the DDS image file format.
/// </summary>
Dds,
/// <summary>
/// Represents an unknown image file format.
/// </summary>
Unknown
}
/// <summary>
/// Static helper class to determine the format of an image file.
/// </summary>
public static class ImageFile
{
private static readonly byte[] ktx1Identifier = { 0xAB, 0x4B, 0x54, 0x58, 0x20, 0x31, 0x31, 0xBB, 0x0D, 0x0A, 0x1A, 0x0A };
/// <summary>
/// Determines the image file format of the given stream.
/// </summary>
/// <param name="stream">The stream of data to identify.</param>
/// <returns>The format this image file may contain.</returns>
public static ImageFileFormat DetermineImageFormat(Stream stream)
{
if (IsDds(stream))
{
return ImageFileFormat.Dds;
}
if (IsKtx(stream))
{
return ImageFileFormat.Ktx;
}
return ImageFileFormat.Unknown;
}
private static bool IsDds(Stream stream)
{
using var br = new BinaryReader(stream, Encoding.UTF8, true);
var magic = br.ReadUInt32();
stream.Position -= 4;
return magic == 0x20534444U;
}
private static bool IsKtx(Stream stream)
{
// Only checks for version 1
using var br = new BinaryReader(stream, Encoding.ASCII, true);
var identifier = br.ReadBytes(12);
stream.Position -= 12;
return identifier.SequenceEqual(ktx1Identifier);
}
}
}