render_to_tga.cpp 1.7 KB

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