Unity texture utilities
public static Texture2D LoadDDS(byte[] data, TextureFormat textureFormat, bool mipmaps = false)
{
if (textureFormat != TextureFormat.DXT1 && textureFormat != TextureFormat.DXT5)
{
throw new Exception("Invalid TextureFormat. Only DXT1 and DXT5 formats are supported by this method.");
}
byte ddsSizeCheck = data[4];
if (ddsSizeCheck != 124)
{
throw new Exception("Invalid DDS DXTn texture. Unable to read"); //this header byte should be 124 for DDS image files
}
int height = data[13] * 256 + data[12];
int width = data[17] * 256 + data[16];
int DDS_HEADER_SIZE = 128;
byte[] dxtBytes = new byte[data.Length - DDS_HEADER_SIZE];
Buffer.BlockCopy(data, DDS_HEADER_SIZE, dxtBytes, 0, data.Length - DDS_HEADER_SIZE);
Texture2D texture = new Texture2D(width, height, textureFormat, mipmaps);
texture.LoadRawTextureData(dxtBytes);
texture.Apply();
return (texture);
}
public static Texture2D LoadCRN(byte[] data, bool mipmaps = false)
{
ushort width = System.BitConverter.ToUInt16(new byte[2] { data[13], data[12] }, 0);
ushort height = System.BitConverter.ToUInt16(new byte[2] { data[15], data[14] }, 0);
byte format = data[18];
TextureFormat textureFormat = TextureFormat.RGB24;
if (format == 0)
{
textureFormat = TextureFormat.DXT1Crunched;
}
else if (format == 2)
{
textureFormat = TextureFormat.DXT5Crunched;
}
else
{
throw new System.Exception("Not supported format");
}
Texture2D texture = new Texture2D(width, height, textureFormat, mipmaps);
texture.LoadRawTextureData(data);
texture.Apply();
return texture;
}