FloatImg/lib/fimg-pnm.c

138 lines
2.7 KiB
C

/*
* fimg-pnm.c
*
*
*/
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include "string.h"
#include "../floatimg.h"
extern int verbosity; /* must be declared around main() */
/* ---------------------------------------------------------------- */
/* nouveau juin 2019, pendant la Ravebish */
int fimg_load_from_pnm(char *fname, FloatImg *head, int notused)
{
FILE *fp;
int width, height, maxval;
int foo, line, column;
unsigned char *buffline, *idxrd;
float *Rptr, *Gptr, *Bptr;
if (NULL==head) {
fprintf(stderr, "%s : head ptr is %p\n", __func__, head);
return -8;
}
if (NULL==(fp=fopen(fname, "r"))) {
perror(fname);
exit(1);
}
foo = fscanf(fp, "P6 %d %d %d", &width, &height, &maxval);
if (3 != foo) {
fprintf(stderr, "%s : fscanf -> %d\n", __func__, foo);
return -1;
}
if (verbosity) {
fprintf(stderr, "%s is %dx%d , max=%d\n",fname, width, height, maxval);
}
if (NULL==(buffline=calloc(3, width))) {
fprintf(stderr, "%s on %s : memory error\n", __func__, fname);
return -2;
}
foo = fimg_create(head, width, height, 3);
if (foo) {
fprintf(stderr, "%s : create floatimg -> %d\n", __func__, foo);
exit(1);
}
fseek(fp, 1L, SEEK_CUR); /* black magic */
Rptr = head->R; Gptr = head->G; Bptr = head->B;
for (line=0; line<height; line++) {
foo = fread(buffline, 3, width, fp);
// fprintf(stderr, "line %d read %d\n", line, width);
idxrd = buffline;
for (column=0; column<width; column++)
{
*Rptr++ = (float)*idxrd++;
*Gptr++ = (float)*idxrd++;
*Bptr++ = (float)*idxrd++;
}
}
fclose(fp);
return 0;
}
/* ---------------------------------------------------------------- */
int fimg_save_as_pnm(FloatImg *head, char *fname, int notused)
{
FILE *fp;
float maximum, fk;
int idx, sz, Rv, Gv, Bv, foo;
#if DEBUG_LEVEL
fprintf(stderr, ">>> %-25s ( %p '%s' %d )\n", __func__, head,
fname, notused);
#endif
if (head->type != 3) {
#if DEBUG_LEVEL
fprintf(stderr, "%s : type %d is bad.\n", __func__, head->type);
#endif
return -1;
}
if (NULL==(fp=fopen(fname, "w"))) {
perror(fname);
return -1;
}
fprintf(fp, "P3\n%d %d\n", head->width, head->height);
maximum = fimg_get_maxvalue(head);
fprintf(fp, "# maxval %15f\n", maximum);
fk = maximum / 65536.0;
fprintf(fp, "# divisor %15f\n", fk);
fprintf(fp, "65535\n");
sz = head->width*head->height;
foo = 0;
for (idx=0; idx<sz; idx++) {
if (fk > 0) {
Rv = (int)(head->R[idx] / fk);
Gv = (int)(head->G[idx] / fk);
Bv = (int)(head->B[idx] / fk);
}
else {
Rv = Gv = Bv = 0;
}
foo += fprintf(fp, "%d %d %d", Rv, Gv, Bv);
if (foo > 60) {
fputs("\n", fp); foo = 0;
}
else {
fputs(" ", fp); foo++;
}
}
fputs("\n", fp);
fclose(fp);
return 0;
}
/* ---------------------------------------------------------------- */