segmentation default
take what you need
Thursday, 15 December 2011
Write a ppm file picture
Write a picture ppm file to memory.
To make it faster, use mmap so that the memory writes itself back to a file at the end.
#include <sys/mman.h> #include <unistd.h> #include <assert.h> #include <stdlib.h> #include <string.h> const int COLOR_NO = 256; // Pixel color range const int MAX_COLOR = COLOR_NO - 1; const int COLUMNS = 30; // Pixel Columns number const int ROWS = 30; // Pixel Rows number const int STRING_DIM = COLUMNS * ROWS * 20; // Big enough const char filename[] = "newPic.ppm"; // Destination file // New file of the specified size void makeNewFile(const char * filename, int length){ // New File FILE * fileToWrite; fileToWrite = fopen( filename,"w"); if( fileToWrite != NULL){ for(int i = 0; i < length; i++){ fputc(' ',fileToWrite); } } fclose(fileToWrite); } // Making a String in ppm format: http://netpbm.sourceforge.net/doc/ppm.html void createPpmFormat(char * res){ res = strcat(res, "P3\n"); // Ppm format char temp[STRING_DIM]; // A string Big enough sprintf(temp,"%d %d\n%d\n",COLUMNS, ROWS, MAX_COLOR); // Ppm dimension and color strcat(res, temp); int a[3]; for(int i = 0; i < ROWS; i++){ // Randomly coloring pixels for(int j = 0; j < COLUMNS; j++){ a[0] = rand() % COLOR_NO; a[1] = rand() % COLOR_NO; a[2] = rand() % COLOR_NO; sprintf(temp," %d %d %d ", a[0],a[1],a[2]); strcat(res,temp); } strcat(res,"\n"); } } int main() { makeNewFile( filename, STRING_DIM); // Creating a file big enough int f = open(filename, O_RDWR); // read - write assert ( f >=0); // newPic.ppm must exist before this starts. Its contents will be changed. char * pos = (char*) mmap(0, STRING_DIM + 1, PROT_READ | PROT_WRITE, MAP_SHARED, f, 0); assert (pos != MAP_FAILED); char * ppmFormat = (char*)malloc(sizeof(char) * (STRING_DIM+1)); createPpmFormat( ppmFormat); // Writing the ppm format string in memory for (int j = 0 ; j < STRING_DIM; ++j) pos[j] = ppmFormat[j]; printf("\n"); return 0; } <textarea/>
No comments:
Post a Comment
Newer Post
Older Post
Home
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment