texture_from_png.cpp 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. // This file is part of libigl, a simple c++ geometry processing library.
  2. //
  3. // Copyright (C) 2014 Alec Jacobson <alecjacobson@gmail.com>
  4. //
  5. // This Source Code Form is subject to the terms of the Mozilla Public License
  6. // v. 2.0. If a copy of the MPL was not distributed with this file, You can
  7. // obtain one at http://mozilla.org/MPL/2.0/.
  8. #include "texture_from_png.h"
  9. #include "../opengl/report_gl_error.h"
  10. #include <stb_image.h>
  11. IGL_INLINE bool igl::png::texture_from_png(const std::string png_file, const bool flip, GLuint & id)
  12. {
  13. int width,height,n;
  14. unsigned char *data = stbi_load(png_file.c_str(), &width, &height, &n, 4);
  15. if(data == NULL) {
  16. return false;
  17. }
  18. // Why do I need to flip?
  19. /*if(flip)
  20. {
  21. yimg.flip();
  22. }*/
  23. glGenTextures(1, &id);
  24. glBindTexture(GL_TEXTURE_2D, id);
  25. glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP);
  26. glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP);
  27. glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
  28. glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
  29. glTexImage2D(
  30. GL_TEXTURE_2D, 0, GL_RGB,
  31. width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, data);
  32. glBindTexture(GL_TEXTURE_2D, 0);
  33. stbi_image_free(data);
  34. return true;
  35. }
  36. IGL_INLINE bool igl::png::texture_from_png(const std::string png_file, GLuint & id)
  37. {
  38. return texture_from_png(png_file,false,id);
  39. }
  40. IGL_INLINE bool igl::png::texture_from_png(
  41. const std::string png_file,
  42. Eigen::Matrix<char,Eigen::Dynamic,Eigen::Dynamic>& R,
  43. Eigen::Matrix<char,Eigen::Dynamic,Eigen::Dynamic>& G,
  44. Eigen::Matrix<char,Eigen::Dynamic,Eigen::Dynamic>& B,
  45. Eigen::Matrix<char,Eigen::Dynamic,Eigen::Dynamic>& A
  46. )
  47. {
  48. int width,height,n;
  49. unsigned char *data = stbi_load(png_file.c_str(), &width, &height, &n, 4);
  50. if(data == NULL) {
  51. return false;
  52. }
  53. R.resize(height,width);
  54. G.resize(height,width);
  55. B.resize(height,width);
  56. A.resize(height,width);
  57. for (unsigned j=0; j<height; ++j) {
  58. for (unsigned i=0; i<width; ++i) {
  59. // used to flip with libPNG, but I'm not sure if
  60. // simply j*width + i wouldn't be better
  61. // stb_image uses horizontal scanline an starts top-left corner
  62. R(i,j) = data[4*( (width-1-i) + width * (height-1-j) )];
  63. G(i,j) = data[4*( (width-1-i) + width * (height-1-j) ) + 1];
  64. B(i,j) = data[4*( (width-1-i) + width * (height-1-j) ) + 2];
  65. //A(i,j) = data[4*( (width-1-i) + width * (height-1-j) ) + 3];
  66. }
  67. }
  68. stbi_image_free(data);
  69. return true;
  70. }