MB_TGAWriter.cs 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. using UnityEngine;
  2. using System.Collections;
  3. using System;
  4. using System.IO;
  5. namespace DigitalOpus.MB.Core
  6. {
  7. public static class MB_TGAWriter
  8. {
  9. public static void Write(Color[] pixels, int width, int height, string path)
  10. {
  11. // Delete the file if it exists.
  12. if (File.Exists(path))
  13. {
  14. File.Delete(path);
  15. }
  16. //Create the file.
  17. FileStream fs = File.Create(path);
  18. Write(pixels, width, height, fs);
  19. }
  20. public static void Write(Color[] pixels, int width, int height, Stream output)
  21. {
  22. byte[] pixelsArr = new byte[pixels.Length * 4];
  23. int offsetSource = 0;
  24. int offsetDest = 0;
  25. for (int y = 0; y < height; y++)
  26. {
  27. for (int x = 0; x < width; x++)
  28. {
  29. Color value = pixels[offsetSource];
  30. pixelsArr[offsetDest] = (byte)(value.b * 255); // b
  31. pixelsArr[offsetDest + 1] = (byte)(value.g * 255); // g
  32. pixelsArr[offsetDest + 2] = (byte)(value.r * 255); // r
  33. pixelsArr[offsetDest + 3] = (byte)(value.a * 255); // a
  34. offsetSource++;
  35. offsetDest += 4;
  36. }
  37. }
  38. byte[] header = new byte[] {
  39. 0, // ID length
  40. 0, // no color map
  41. 2, // uncompressed, true color
  42. 0, 0, 0, 0,
  43. 0,
  44. 0, 0, 0, 0, // x and y origin
  45. (byte)(width & 0x00FF),
  46. (byte)((width & 0xFF00) >> 8),
  47. (byte)(height & 0x00FF),
  48. (byte)((height & 0xFF00) >> 8),
  49. 32, // 32 bit bitmap
  50. 0 };
  51. using (BinaryWriter writer = new BinaryWriter(output))
  52. {
  53. writer.Write(header);
  54. writer.Write(pixelsArr);
  55. }
  56. }
  57. }
  58. }