Für Vorlesungen, bitte die Webseite verwenden. https://flavigny.de/lecture
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

65 line
1.5KB

  1. #include <string>
  2. #include <fstream>
  3. #include <cmath>
  4. void write_pgm(int* pixels, int horPixels, int vertPixels, std::string filename)
  5. {
  6. if(horPixels == 0 || vertPixels == 0)
  7. {
  8. std::cerr << "Leeres Pixel Array" << std::endl;
  9. return;
  10. }
  11. // write file
  12. // unfortunately we cannot use C++-11 which would simplify our life in that case
  13. std::ofstream outfile;
  14. outfile.open(filename.c_str());
  15. outfile << "P2" << std::endl
  16. << horPixels << " " << vertPixels << std::endl;
  17. // renormalize if necessary
  18. int maxVal = 0;
  19. for(int entry=0; entry<horPixels*vertPixels; entry++)
  20. maxVal = std::max(pixels[entry],maxVal);
  21. // renormalizing output
  22. if(maxVal > 65535)
  23. {
  24. outfile << 65535 << std::endl;
  25. for(int j=0, entry=0; j<vertPixels; j++)
  26. {
  27. for(int i=0; i<horPixels; i++, entry++)
  28. {
  29. if(pixels[entry] < 0)
  30. {
  31. std::cerr << "Negativer Eintrag bei (" << i << ", " << j << ")" << std::endl;
  32. return;
  33. }
  34. outfile << std::floor(pixels[entry] * (65535./maxVal)) << " ";
  35. }
  36. outfile << std::endl;
  37. }
  38. }
  39. // normal output
  40. else
  41. {
  42. outfile << maxVal << std::endl;
  43. for(int j=0; j<vertPixels; j++)
  44. {
  45. for(int i=0; i<horPixels; i++)
  46. {
  47. int entry = i + horPixels*(vertPixels-1-j);
  48. if(pixels[entry] < 0)
  49. {
  50. std::cerr << "Negativer Eintrag bei (" << i << ", " << j << ")" << std::endl;
  51. return;
  52. }
  53. outfile << pixels[entry] << " ";
  54. }
  55. outfile << std::endl;
  56. }
  57. }
  58. outfile.close();
  59. }