Last active
September 11, 2015 02:34
-
-
Save robdanet/b01bee9fcb4e735db4c5 to your computer and use it in GitHub Desktop.
Source code for blog post http://thesourcecodenotes.blogspot.co.uk/2015/09/create-image-and-pixel-structure-for.html The code creates a 256x256 PPM image with a white background and only on red pixel located in the center of it.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
Source code for blog post http://thesourcecodenotes.blogspot.co.uk/2015/09/create-image-and-pixel-structure-for.html | |
The code creates a 256x256 PPM image with a white background and only one red pixel located in the center of it. | |
by Antonio Molinaro, 2015. | |
*/ | |
#include <stdio.h> | |
#include <stdlib.h> | |
#include <string.h> | |
typedef struct { | |
unsigned char r,g,b; | |
}Pixel; | |
typedef struct { | |
unsigned int width, height; | |
Pixel * data; | |
}Image; | |
unsigned int getImgWidth(const Image * i){ return i->width; } | |
unsigned int getImgHeight(const Image * i){ return i->height; } | |
void setPixel(int x, int y, Image ** data, const Pixel data_new) | |
{ | |
Pixel * p = (*data)->data; | |
p[x + y * getImgWidth(*data)].r = data_new.r; | |
p[x + y * getImgWidth(*data)].g = data_new.g; | |
p[x + y * getImgWidth(*data)].b = data_new.b; | |
} | |
int main() { | |
char filename[80] = "myimage2.ppm"; | |
//create and open image file | |
FILE * fp = fopen(filename, "wb"); | |
if (!fp) { | |
fprintf(stderr, "Unable to open file '%s'\n", filename); | |
exit(1); | |
} | |
//allocate immage memory | |
Image * i = malloc(sizeof(Image)); | |
if(!i) { | |
fprintf(stderr, "Unable to allocate memory\n"); | |
fclose(fp); | |
exit(1); | |
} | |
//initialize image structure | |
i->width = 256; | |
i->height = 256; | |
//allocate pixels memory | |
i->data = malloc(sizeof(Pixel) * getImgWidth(i) * getImgHeight(i)); | |
if(!i->data) { | |
fprintf(stderr, "Unable to allocate memory\n"); | |
fclose(fp); | |
exit(1); | |
} | |
//set all image's pixels to 255 | |
memset(i->data, 255, sizeof(Pixel) * getImgWidth(i) * getImgHeight(i)); | |
//initialize a pixel to red | |
Pixel red = {255,0,0}; | |
//and set with it the central pixel of the image | |
setPixel(getImgWidth(i)/2, getImgHeight(i)/2, &i, red); | |
//write the image header to the file | |
fprintf(fp, "P6\n %d\n %d\n 255\n", getImgWidth(i), getImgHeight(i)); | |
//write the image data to file | |
fwrite(i->data, 3, getImgWidth(i) * getImgHeight(i), fp); | |
fclose(fp); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment