render_to_tga.cpp 1.8 KB

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