Skip to content

Commit

Permalink
added TGA saving routines
Browse files Browse the repository at this point in the history
added my old Java code from 2004, ported to C# but needs more testing and polishing
  • Loading branch information
VasilijP committed Oct 16, 2024
1 parent 327c701 commit 7e2aa9e
Show file tree
Hide file tree
Showing 10 changed files with 417 additions and 79 deletions.
43 changes: 22 additions & 21 deletions LICENSE
Original file line number Diff line number Diff line change
@@ -1,21 +1,22 @@
MIT License

Copyright (c) 2016 shns

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
MIT License

Copyright (c) 2016 shns
Copyright (c) 2004-2024 Peter Truchly

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
2 changes: 2 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
# TgaLib core

- Forked from *shns/TgaLib:master* in order to upgrade project file for .Net 8
- Removed platform specific parts so this could work on non-Windows OS.
- Added my old (2004 / Java) implementation for saving&loading of 24bit RGB TGA images.

# TgaLib

Expand Down
6 changes: 3 additions & 3 deletions tga-info/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -6,9 +6,9 @@ internal static class Program
{
private static void Main(string[] args)
{
using FileStream fs = new FileStream(args[0], FileMode.Open, FileAccess.Read, FileShare.Read);
using BinaryReader reader = new BinaryReader(fs);
TgaImage tga = new TgaImage(reader);
using FileStream fs = new(args[0], FileMode.Open, FileAccess.Read, FileShare.Read);
using BinaryReader reader = new(fs);
TgaImage tga = new(reader);
Console.WriteLine($"{tga}");
}
}
Expand Down
73 changes: 73 additions & 0 deletions tgalib-core.Tests/TgaFileFormatTests.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
using System.IO;
using NUnit.Framework;

namespace tgalib_core.Tests;

[TestFixture]
public class TgaFileFormatTests
{
[Test]
[TestCase("resources/CBW8.TGA")]
public void Test01_LoadSaveRgb24Rle(string filename)
{
using FileStream ts = new(filename, FileMode.Open, FileAccess.Read, FileShare.Read);
using BinaryReader r = new(ts);
TgaImage tga = new(r);
Image actualImage = tga.GetImage();

TgaFileFormat tff = new();
using FileStream fs = File.OpenWrite("test01.tga");
tff.CommonSave(TgaMode.Rgb24Rle, fs, actualImage);
fs.Close();
// Assert.Pass();
}

[Test]
[TestCase("resources/UBW8.TGA", false)]
[TestCase("resources/UCM8.TGA", false)]
[TestCase("resources/UTC16.TGA", false)]
[TestCase("resources/UTC24.TGA", false)]
[TestCase("resources/UTC32.TGA", false)]
[TestCase("resources/UBW8.TGA", true)]
[TestCase("resources/CBW8.TGA", false)]
[TestCase("resources/CCM8.TGA", false)]
[TestCase("resources/CTC16.TGA", false)]
[TestCase("resources/CTC24.TGA", false)]
[TestCase("resources/CTC32.TGA", false)]
[TestCase("resources/rgb32rle.tga", true)]
public void Test02_RoundTripRgb24Rle(string filename, bool forceAlpha)
{
using FileStream ts = new(filename, FileMode.Open, FileAccess.Read, FileShare.Read);
using BinaryReader br = new(ts);
TgaImage tga = new(br, forceAlpha);
Image actualImage = tga.GetImage();

TgaFileFormat tff = new();
using FileStream fs = File.OpenWrite("test02.tga");
tff.CommonSave(TgaMode.Rgb24Rle, fs, actualImage);
fs.Close();

using FileStream ts2 = new("test02.tga", FileMode.Open, FileAccess.Read, FileShare.Read);
using BinaryReader br2 = new(ts2);
TgaImage tga2 = new(br2, forceAlpha);
Image actualImage2 = tga2.GetImage();

int width = actualImage.Width;
int height = actualImage.Height;

Assert.That(width, Is.EqualTo(actualImage2.Width));
Assert.That(height, Is.EqualTo(actualImage2.Height));

for (int x = 0; x < width; x++)
{
for (int y = 0; y < height; y++)
{
actualImage.GetPixelRgba(x, y, out int r1, out int g1, out int b1, out int a1);
actualImage2.GetPixelRgba(x, y, out int r2, out int g2, out int b2, out int a2);
Assert.That(r1, Is.EqualTo(r2));
Assert.That(g1, Is.EqualTo(g2));
Assert.That(b1, Is.EqualTo(b2));
}
}
}
}
60 changes: 25 additions & 35 deletions tgalib-core/Constants.cs
Original file line number Diff line number Diff line change
Expand Up @@ -31,58 +31,48 @@ public static string ToFormattedText(byte value)
}
}

public enum TgaMode : byte
{
NoImage = 0, // No image data included.
ColorMapped = 1, // Uncompressed, color-mapped image.
Pal8Unc = 1, //color mapped uncompressed
TrueColor = 2, // Uncompressed, true-color image.
Rgb24Unc = 2, //rgb uncompressed
Monochrome = 3, // Uncompressed, black and white image.
CompressedColorMapped = 9, // Run-length encoded, color-mapped image.
Pal8Rle = 9, //rle color mapped
CompressedTrueColor = 10, // Run-length encoded, true-color image.
Rgb24Rle = 10, //Runlength encoded RGB
CompressedMonochrome = 11 // Run-length encoded, black and white image.
}

/// <summary>
/// Image type.
/// </summary>
public static class ImageTypes
{
/// <summary>No image data included.</summary>
public const byte NoImage = 0;

/// <summary>Uncompressed, color-mapped image.</summary>
public const byte ColorMapped = 1;

/// <summary>Uncompressed, true-color image.</summary>
public const byte TrueColor = 2;

/// <summary>Uncompressed, black and white image.</summary>
public const byte Monochrome = 3;

/// <summary>Run-length encoded, color-mapped image.</summary>
public const byte CompressedColorMapped = 9;

/// <summary>Run-length encoded, true-color image.</summary>
public const byte CompressedTrueColor = 10;

/// <summary>Run-length encoded, black and white image.</summary>
public const byte CompressedMonochrome = 11;

/// <summary>
/// Formatted text.
/// </summary>
private static readonly Dictionary<byte, string> FormattedText = new Dictionary<byte, string>()
private static readonly Dictionary<TgaMode, string> FormattedText = new()
{
{ NoImage, "no image" },
{ ColorMapped, "color-mapped(uncompressed)" },
{ TrueColor, "true-color(uncompressed)" },
{ Monochrome, "monochrome(uncompressed)" },
{ CompressedColorMapped, "color-mapped(RLE)" },
{ CompressedTrueColor, "true-color(RLE)" },
{ CompressedMonochrome, "monochrome(RLE)" },
{ TgaMode.NoImage, "no image" },
{ TgaMode.ColorMapped, "color-mapped(uncompressed)" },
{ TgaMode.TrueColor, "true-color(uncompressed)" },
{ TgaMode.Monochrome, "monochrome(uncompressed)" },
{ TgaMode.CompressedColorMapped, "color-mapped(RLE)" },
{ TgaMode.CompressedTrueColor, "true-color(RLE)" },
{ TgaMode.CompressedMonochrome, "monochrome(RLE)" },
};

/// <summary>
/// Returns a formatted text.
/// </summary>
/// <param name="value">An image type value.</param>
/// <returns>Returns a formatted text.</returns>
public static string ToFormattedText(byte value)
public static string ToFormattedText(TgaMode value)
{
if (!FormattedText.ContainsKey(value))
{
return "???";
}
return FormattedText[value];
return FormattedText.GetValueOrDefault(value, "???");
}
}

Expand Down
71 changes: 71 additions & 0 deletions tgalib-core/RleCompressor.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
namespace tgalib_core;

//auxiliary class for RLE compression
public class RleCompressor(Stream stream)
{
private const int buflen = 65536;
private const int bufcritical = 65532;
private RlePixel[] buf = new RlePixel[buflen];
private int bufindex = 0;//index of first free place

private bool match(RlePixel arg1, RlePixel arg2)
{
if (arg1.c.Length != arg2.c.Length) return(false);
for (int i = 0; i < arg1.c.Length; i++) if (arg1.c[i] != arg2.c[i]) return(false);
return(true);
}

public void write(byte arg) { write([arg]); }

//add arg to FIFO
public void write(byte[] arg)
{
RlePixel argpix = new RlePixel(arg);
if ((bufindex > 0)&&match(buf[bufindex-1],argpix)){
if (buf[bufindex-1].rep < 128){
buf[bufindex-1].rep++;
return;
}
}
buf[bufindex]=argpix;
bufindex++;
if (bufindex > bufcritical) forceWrite();
}

//write one copy or run packet
private void writePacket(int from, int to)
{
byte[] header = new byte[1];
if (to - from > 0) //create copy packet
{
header[0] = (byte)(to - from);//number of copied pixels - 1
} else { //write run packet
header[0] = (byte)(128 | (buf[from].rep-1));//number of repetition -1 and highest bit is 1
}
try
{
stream.Write(header);
for (int rpc = from; rpc <= to; rpc++) // this should run only once for run packet
{
stream.Write(buf[rpc].c);
}
} catch (IOException e) { Console.WriteLine(e); }
}

//forced write of entire buffer to output (end of image or full buffer)
public void forceWrite()
{
int from = 0;
while (from < bufindex)
{
int to = from;
while ((to < bufindex-1)&&(buf[to].rep == 1)&&(to-from < 127)) to++;
if ((to - from +1 > 1)&&(buf[to].rep > 1)) to--;
writePacket(from, to);
from = to+1;
//writePacket(from, from);
//from++;
}
bufindex = 0;//empty buffer
}
}
8 changes: 8 additions & 0 deletions tgalib-core/RlePixel.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
namespace tgalib_core;

// Pixel value with repetition count.
public class RlePixel(byte[] arg)
{
public byte[] c = arg;
public int rep = 1;
}
Loading

0 comments on commit 7e2aa9e

Please sign in to comment.