1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73
|
//Conversion image PPM P3 en PGM P2
#include<stdio.h>
#include<stdlib.h>
unsigned char *ppm3_load(const char *filename, int *w, int *h)
{
unsigned char *pix = 0;
FILE *f_in = fopen(filename, "r");
if(f_in) {
char buf[32];
if(fgets(buf, sizeof buf, f_in)) {
if(buf[0] == 'P' && buf[1] == '3') {
int c = getc(f_in);
while(c == '#') {
while(getc(f_in) != '\n');
c = getc(f_in);
}
ungetc(c, f_in);
if(fscanf(f_in, "%d %d", w, h) == 2) {
int max;
if(fscanf(f_in, "%d", &max) == 1) {
while(fgetc(f_in) != '\n');
if(max == 255) {
if((pix = malloc(*w * *h * 3))) {
int i, r, g, b;
for(i = 0; fscanf(f_in, "%d %d %d", &r, &g, &b) == 3; i += 3) {
pix[i] = (unsigned char)r;
pix[i + 1] = (unsigned char)g;
pix[i + 2] = (unsigned char)b;
}
}
}
}
}
}
}
fclose(f_in);
}
return pix;
}
int ppm3_to_pgm2(unsigned char *ppm3pix, int width, int height, const char *pgm2name)
{
int i;
FILE *f_out = fopen(pgm2name, "w");
if(f_out) {
fprintf(f_out, "P2\n#by magma\n%d %d\n255\n", width, height);
for(i = 0; i < width * height * 3; i += 3)
fprintf(f_out, "%d\n", (ppm3pix[i] + ppm3pix[i + 1] + ppm3pix[i + 2]) / 3);
fclose(f_out);
return 1;
}
return 0;
}
int main(void)
{
int w, h;
unsigned char *ppm3pix = ppm3_load("image_ppm_P3.ppm", &w, &h);
if(ppm3pix){
printf("%d x %d\n", w, h);
printf("Conversion PPM3 en PGM2 : %s\n", ppm3_to_pgm2(ppm3pix, w, h, "image_pgm_P2.pgm") ? "Ok" : "Echec !");
free(ppm3pix);
}
return 0;
} |
Partager