ITPub博客

首页 > 应用开发 > > c语言读取ppm图像格式

c语言读取ppm图像格式

作者:supersea 时间:2019-09-11 16:32:20 0 删除 编辑
typedef struct {
     unsigned char red,green,blue;
} PPMPixel;

typedef struct {
     int width, height;
     PPMPixel *data;
} PPMImage;
int CudaJpegCode::readPpmFile(const char *ppmfile)
{
    char buff[16];
    FILE *fp;
    int c, rgb_comp_color;
         //open PPM file for reading
    fp = fopen(ppmfile, "rb");
    if (!fp) 
    {
        fprintf(stderr, "Unable to open file '%s'\n", ppmfile);
         exit(1);
    }

    //read image format
    if (!fgets(buff, sizeof(buff), fp)) 
    {
           perror(ppmfile);
              exit(1);
    }

    //check the image format
    if (buff[0] != 'P' || buff[1] != '6') {
         fprintf(stderr, "Invalid image format (must be 'P6')\n");
         exit(1);
    }
    printf(">>>>>>format:%c%c\n",buff[0],buff[1]);
    //alloc memory form image
    m_ppmimg = (PPMImage *)malloc(sizeof(PPMImage));
    if (!m_ppmimg) {
         fprintf(stderr, "Unable to allocate memory\n");
         exit(1);
    }

    //check for comments
    c = getc(fp);
    while (c == '#') {
    while (getc(fp) != '\n') ;
         c = getc(fp);
    }

    ungetc(c, fp);
    //read image size information
    if (fscanf(fp, "%d %d", &m_ppmimg->width, &m_ppmimg->height) != 2) {
         fprintf(stderr, "Invalid image size (error loading '%s')\n", ppmfile);
         exit(1);
    }
    printf(">>>>>width:%d,height=%d\n",m_ppmimg->width,m_ppmimg->height);
    //read rgb component
    if (fscanf(fp, "%d", &rgb_comp_color) != 1) {
         fprintf(stderr, "Invalid rgb component (error loading '%s')\n", ppmfile);
         exit(1);
    }
    printf(">>>>>rgb_comp_color===%d\n",rgb_comp_color);
    //check rgb component depth
    if ( RGB_COMPONENT_COLOR) {
         fprintf(stderr, "'%s' does not have 8-bits components\n", ppmfile);
         exit(1);
    }

    while (fgetc(fp) != '\n') ;
    //memory allocation for pixel data
    m_ppmimg->data = (PPMPixel*)malloc(m_ppmimg->width * m_ppmimg->height * sizeof(PPMPixel));

    if (!m_ppmimg) {
         fprintf(stderr, "Unable to allocate memory\n");
         exit(1);
    }

    //read pixel data from file
    fread(m_ppmimg->data, sizeof(PPMPixel) ,m_ppmimg->width*m_ppmimg->height, fp);
    fclose(fp);
}


来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/2650/viewspace-3130431/ ,如需转载,请注明出处,否则将追究法律责任。

请登录后发表评论 登录
全部评论

注册时间:2019-08-16

  • 博文量
    90
  • 访问量
    799