File indexing completed on 2026-04-09 07:49:44
0001 #pragma once
0002
0003
0004
0005
0006
0007
0008 #include <cassert>
0009 #include <fstream>
0010 #include <iostream>
0011
0012
0013 struct sppm
0014 {
0015 static unsigned char* CreateThreeComponentImage( int width, int height, int ncomp, const unsigned char* image, bool yflip );
0016 static void Write(const char* path, int width, int height, int ncomp, const unsigned char* image, bool yflip);
0017 static unsigned char* CreateImageData( int width, int height, int ncomp );
0018 };
0019
0020
0021
0022
0023
0024
0025
0026
0027
0028
0029 inline unsigned char* sppm::CreateThreeComponentImage( int width, int height, int ncomp, const unsigned char* image, bool yflip )
0030 {
0031 assert( ncomp == 3 || ncomp == 4 );
0032 unsigned size = height*width*3 ;
0033 unsigned char* data = new unsigned char[size] ;
0034 for( int h=0 ; h < height ; h++ )
0035 {
0036 int y = yflip ? height - 1 - h : h ;
0037
0038 for( int x=0; x < width ; ++x )
0039 {
0040 *(data + (y*width+x)*3+0) = image[(h*width+x)*ncomp+0] ;
0041 *(data + (y*width+x)*3+1) = image[(h*width+x)*ncomp+1] ;
0042 *(data + (y*width+x)*3+2) = image[(h*width+x)*ncomp+2] ;
0043 }
0044 }
0045 return data ;
0046 }
0047
0048 inline void sppm::Write(const char* path, int width, int height, int ncomp, const unsigned char* image, bool yflip)
0049 {
0050 FILE * fp;
0051 fp = fopen(path, "wb");
0052
0053 if(!fp) std::cout << "sppm::Write FAILED FOR [" << ( path ? path : "-" ) << std::endl ;
0054 assert(fp);
0055 fprintf(fp, "P6\n%d %d\n%d\n", width, height, 255);
0056
0057 unsigned char* data = CreateThreeComponentImage( width, height, ncomp, image, yflip );
0058 size_t size_in_bytes = height*width*3*sizeof(unsigned char) ;
0059 size_t count = 1 ;
0060 fwrite(data, size_in_bytes, count , fp);
0061 fclose(fp);
0062
0063 delete[] data;
0064 }
0065
0066 inline unsigned char* sppm::CreateImageData( int width, int height, int ncomp )
0067 {
0068 size_t size = height*width*ncomp ;
0069 unsigned char* data = new unsigned char[size] ;
0070 for( int h=0; h < height ; h++ )
0071 {
0072 for( int w=0; w < width ; ++w )
0073 {
0074 for( int k=0 ; k < ncomp ; k++ ) data[ (h*width+w)*ncomp + k] = k < 3 ? 0xaa : 0xff ;
0075 }
0076 }
0077 return data ;
0078 }
0079