tgaimage.h 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101
  1. #ifndef __IMAGE_H__
  2. #define __IMAGE_H__
  3. #include <fstream>
  4. #pragma pack(push,1)
  5. struct TGA_Header {
  6. char idlength;
  7. char colormaptype;
  8. char datatypecode;
  9. short colormaporigin;
  10. short colormaplength;
  11. char colormapdepth;
  12. short x_origin;
  13. short y_origin;
  14. short width;
  15. short height;
  16. char bitsperpixel;
  17. char imagedescriptor;
  18. };
  19. #pragma pack(pop)
  20. struct TGAColor {
  21. unsigned char bgra[4];
  22. unsigned char bytespp;
  23. TGAColor() : bytespp(1)
  24. {
  25. for (int i=0; i<4; i++)
  26. bgra[i] = 0;
  27. }
  28. TGAColor(unsigned char R, unsigned char G, unsigned char B, unsigned char A=255) : bytespp(4) {
  29. bgra[0] = B;
  30. bgra[1] = G;
  31. bgra[2] = R;
  32. bgra[3] = A;
  33. }
  34. TGAColor(unsigned char v) : bytespp(1) {
  35. for (int i=0; i<4; i++) bgra[i] = 0;
  36. bgra[0] = v;
  37. }
  38. TGAColor(const unsigned char *p, unsigned char bpp) : bytespp(bpp) {
  39. for (int i=0; i<(int)bpp; i++) {
  40. bgra[i] = p[i];
  41. }
  42. for (int i=bpp; i<4; i++) {
  43. bgra[i] = 0;
  44. }
  45. }
  46. unsigned char& operator[](const int i) { return bgra[i]; }
  47. TGAColor operator *(float intensity) const {
  48. TGAColor res = *this;
  49. intensity = (intensity>1.f?1.f:(intensity<0.f?0.f:intensity));
  50. for (int i=0; i<4; i++) res.bgra[i] = bgra[i]*intensity;
  51. return res;
  52. }
  53. };
  54. class TGAImage {
  55. protected:
  56. unsigned char* data;
  57. int width;
  58. int height;
  59. int bytespp;
  60. bool load_rle_data(std::ifstream &in);
  61. bool unload_rle_data(std::ofstream &out) const;
  62. public:
  63. enum Format {
  64. GRAYSCALE=1, RGB=3, RGBA=4
  65. };
  66. TGAImage();
  67. TGAImage(int w, int h, int bpp);
  68. TGAImage(const TGAImage &img);
  69. bool read_tga_file(const char *filename);
  70. bool write_tga_file(const char *filename, bool rle=true) const;
  71. bool flip_horizontally();
  72. bool flip_vertically();
  73. bool scale(int w, int h);
  74. TGAColor get(int x, int y) const;
  75. bool set(int x, int y, TGAColor &c);
  76. bool set(int x, int y, const TGAColor &c);
  77. ~TGAImage();
  78. TGAImage & operator =(const TGAImage &img);
  79. int get_width();
  80. int get_height();
  81. int get_bytespp();
  82. unsigned char *buffer();
  83. void clear();
  84. };
  85. #endif //__IMAGE_H__