📄 imreadwrite.c
字号:
/*
* Description:
*
* Procedures to read/write an image in PGM format
*/
#include <stdio.h>
#include <fcntl.h>
/*
* constants
*/
#define OK 1
#define ERROR 0
/* forward declarations */
static char imPgmReadChar(int fd);
static int imPgmReadInt(int fd);
/*
* read image. The user needn't allocate image buffer.
*
* Returns OK if success; ERROR, otherwise.
*/
int imRead (
const char *filename, /* name of file image to read */
int *pwidth, /* Nb of columns of the image */
int *pheight, /* Nb of rows of the image */
unsigned char **imgIn) /* Buffer of the image */
{
int fd;
int size, dimx, dimy;
char ImgType[2];
if ((fd=open(filename,O_RDONLY,0666)) == 0) {
fprintf(stderr,"imRead: opening problem\n");
return (ERROR);
}
*imgIn = NULL;
if (read (fd, ImgType, sizeof(ImgType)) != sizeof(ImgType)) {
fprintf (stderr, "imRead: read error\n");
return (ERROR);
}
if (!strncmp (ImgType, "P5", 2)) {
if((dimx = imPgmReadInt(fd)) == 0 ||
(dimy = imPgmReadInt(fd)) == 0 ||
imPgmReadInt(fd) == 0) {
fprintf(stderr,"imRead: bad PGM header\n");
if ( fd != 0 )
close(fd);
return(ERROR);
}
*pwidth = dimx;
*pheight = dimy;
size = dimx * dimy;
if (((*imgIn) = (unsigned char *)malloc(size)) == NULL)
return (ERROR);
if (read (fd, (*imgIn), size) != size) {
fprintf (stderr, "imRead: read size problem\n");
if (fd != 0)
close (fd);
return (ERROR);
}
}
else {
return (ERROR);
}
close (fd);
return (OK);
}
static char imPgmReadChar(int fd) /* opened file descriptor of the file */
{
char c;
if ( read(fd,&c,1) != 1) {
return((char)ERROR);
}
if ( c == '#' ) {
do {
if ( read(fd,&c,1) != 1) {
return((char)ERROR);
}
} while( (c != '\n') && (c != '\r')) ;
}
return (c);
}
static int imPgmReadInt (int fd) /* opened file descriptor of the file */
{
register char ch;
register int i;
do {
ch = imPgmReadChar(fd);
if ( ch == (char) ERROR ) {
return(ERROR);
}
} while ( ch == ' ' || ch == '\t' || ch == '\n' || ch == '\r' );
if ( ch < '0' || ch > '9' ) {
fprintf(stderr,"imRead: problem with PGM format\n");
return(ERROR);
}
i = 0;
do {
i = i * 10 + ch - '0';
ch = imPgmReadChar(fd);
if ( ch == (char) ERROR ) {
return(ERROR);
}
} while ( ch >= '0' && ch <= '9' );
return i;
}
/*
* write image
*
* Returns OK if success; ERROR, otherwise.
*/
int imWrite (
const char *filename, /* name of file image to read */
const int width, /* Nb of columns of the image */
const int height, /* Nb of rows of the image */
unsigned char *imgIn) /* Buffer of the image */
{
int fd;
int size, nbc;
char header[256];
size = width * height;
if ((fd=open(filename,O_WRONLY|O_CREAT,0666)) == 0) {
fprintf(stderr, "imRead: opening problem\n");
return (ERROR);
}
sprintf (header, "P5\n%d %d\n255\n", width, height);
write (fd, header, strlen(header));
nbc = write (fd, imgIn, size);
if (nbc != size) {
fprintf (stderr, "imRead: write size problem\n");
close (fd);
return (ERROR);
}
else {
close (fd);
return (OK);
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -