Archive Browser
Download WestwoodPaletteLoader.zip, last updated 26/12/2017 (27.76 KB)
Download- md5: da29ba80301e3fa413c90a973afdaec9
- sha1: 362ce84dba11d8047dc3c1dc3e44ee2f0edee602
- sha256: 2e31cc54ea412623684856d331851c8b213bc6369629c620a2fc2d44aedae2bd
using System;
using System.Collections;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Linq;
// Reading and writing 18-bit RGB VGA Palette (pal) files with C#
// http://www.cyotek.com/blog/reading-and-writing-18-bit-rgb-vga-palette-pal-files-with-csharp
namespace Cyotek.Demonstrations.Rgb18BitPalette
{
internal sealed class WestwoodPalette : IEnumerable<Color>
{
#region Fields
private Color[] _palette;
#endregion
#region Constructors
public WestwoodPalette()
{
_palette = new Color[0];
}
public WestwoodPalette(IEnumerable<Color> colors)
{
if (colors == null)
{
throw new ArgumentNullException(nameof(colors));
}
_palette = colors.ToArray();
}
#endregion
#region Static Methods
public static WestwoodPalette LoadFrom(string fileName)
{
WestwoodPalette palette;
palette = new WestwoodPalette();
palette.Load(fileName);
return palette;
}
public static WestwoodPalette LoadFrom(Stream stream)
{
WestwoodPalette palette;
palette = new WestwoodPalette();
palette.Load(stream);
return palette;
}
#endregion
#region Properties
public int Count
{
get { return _palette.Length; }
}
public Color this[int index]
{
get { return _palette[index]; }
}
#endregion
#region Methods
public void Load(string fileName)
{
using (Stream stream = File.OpenRead(fileName))
{
this.Load(stream);
}
}
public void Load(Stream stream)
{
int length;
length = (int)(stream.Length / 3);
_palette = new Color[length];
for (int i = 0; i < length; i++)
{
int r;
int g;
int b;
r = stream.ReadByte() << 2;
g = stream.ReadByte() << 2;
b = stream.ReadByte() << 2;
//_palette[i] = Color.FromArgb(r, g, b); // NOTE: Will crash if used with 24-bit palettes
_palette[i] = Color.FromArgb((255 << 24) | (r << 16) | (g << 8) | b);
}
}
public void Save(string fileName)
{
using (Stream stream = File.Create(fileName))
{
this.Save(stream);
}
}
public void Save(Stream stream)
{
for (int i = 0; i < _palette.Length; i++)
{
Color color;
byte r;
byte g;
byte b;
color = _palette[i];
r = (byte)(color.R >> 2);
g = (byte)(color.G >> 2);
b = (byte)(color.B >> 2);
stream.WriteByte(r);
stream.WriteByte(g);
stream.WriteByte(b);
}
}
public Color[] ToArray()
{
return (Color[])_palette.Clone();
}
#endregion
#region IEnumerable<Color> Interface
public IEnumerator<Color> GetEnumerator()
{
return ((IEnumerable<Color>)_palette).GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
return this.GetEnumerator();
}
#endregion
}
}
Donate
This software may be used free of charge, but as with all free software there are costs involved to develop and maintain.
If this site or its services have saved you time, please consider a donation to help with running costs and timely updates.
Donate