render_to_tga.cpp 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. #include "render_to_tga.h"
  2. #include "tga.h"
  3. IGL_INLINE bool igl::render_to_tga(
  4. const std::string tga_file,
  5. const int width,
  6. const int height,
  7. const bool alpha)
  8. {
  9. size_t components = 3;
  10. GLenum format = GL_BGR;
  11. if(alpha)
  12. {
  13. format = GL_BGRA;
  14. components = 4;
  15. }
  16. GLubyte * cmap = NULL;
  17. // OpenGL by default tries to read data in multiples of 4, if our data is
  18. // only RGB or BGR and the width is not divible by 4 then we need to alert
  19. // opengl
  20. if((width % 4) != 0 &&
  21. (format == GL_RGB ||
  22. format == GL_BGR))
  23. {
  24. glPixelStorei(GL_PACK_ALIGNMENT, 1);
  25. }
  26. GLubyte *pixels;
  27. pixels = (unsigned char *) malloc (width * height * components);
  28. glReadPixels(
  29. 0,
  30. 0,
  31. width,
  32. height,
  33. format,
  34. GL_UNSIGNED_BYTE,
  35. pixels);
  36. // set up generic image struct
  37. gliGenericImage * genericImage;
  38. genericImage = (gliGenericImage*) malloc(sizeof(gliGenericImage));
  39. genericImage->width = width;
  40. genericImage->height = height;
  41. genericImage->format = format;
  42. genericImage->components = components;
  43. genericImage->pixels = pixels;
  44. // CMAP is not supported, but we need to put something here
  45. genericImage->cmapEntries = 0;
  46. genericImage->cmapFormat = GL_BGR_EXT; // XXX fix me
  47. genericImage->cmap = cmap;
  48. // write pixels to tga file
  49. FILE * imgFile;
  50. // "-" as output file name is code for write to stdout
  51. if(tga_file.compare("-") == 0)
  52. {
  53. imgFile = stdout;
  54. }else{
  55. imgFile = fopen(tga_file.c_str(),"w");
  56. if(NULL==imgFile)
  57. {
  58. printf("IOError: %s could not be opened...",tga_file.c_str());
  59. return false;
  60. }
  61. }
  62. writeTGA(genericImage,imgFile);
  63. free(genericImage);
  64. return fclose(imgFile) == 0;
  65. }