You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用C语言将.pnm图像缩小至1/2尺寸?技术求助

问题:PNM图像缩放到1/2尺寸失败,仅实现裁剪

我是大学C语言新手,上周缺席了实验课,目前补做实验任务:读取给定的PNM图像文件,将其宽高均缩小至原尺寸的1/2。此前已成功完成PNM图像的读写实验,现有代码基于该实验修改,但缩放逻辑存在问题,输出的图像仅为裁剪效果,而非整体缩放。


头文件 defs.h

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

//header struct
typedef struct info{
        char type[3];
        int width;
        int height;
        int maxColor;
    }info_t;

//struct to hold pixels
typedef struct rgb{
        unsigned int r;
        unsigned int g;
        unsigned int b;
    }rgb_t;

//function prototypes
info_t getHeader();
void writeHeader(info_t headerInfo);
void fillImageArray(rgb_t *pixels, int max);
void writePixels(rgb_t *pixels, int max);
void halfSizeWritePixels(rgb_t *pixels, int max);

fillImageArray 函数

void fillImageArray(rgb_t *pixels, int max){

    for(int a = 0; a < max; a++){
        fscanf(stdin, "%i", &pixels[a].r);
        fscanf(stdin, "%i", &pixels[a].g);
        fscanf(stdin, "%i", &pixels[a].b);
    }
}

getHeader 函数

#include "defs.h"

info_t getHeader(){

    info_t header;
    fscanf(stdin, "%s", &header.type);
    int *z;
    z = (int *) malloc(3 * sizeof(int));
       for(int i = 0; i < 3; i++){
              fscanf(stdin, "%i", &z[i]);
       }
    header.width = z[0];
    header.height = z[1];
    header.maxColor = z[2];

    free(z);

return header;
}

writeHeader 函数

#include"defs.h"

void writeHeader(info_t headerInfo){
    fprintf(stdout, "%s\n", headerInfo.type);
    fprintf(stdout, "%i %i %i\n", (headerInfo.width/2), (headerInfo.height/2), headerInfo.maxColor); 
}

halfSizeWritePixels 函数

#include"defs.h"

void halfSizeWritePixels(rgb_t *pixels, int max){

    for(int b = 0; b < max; b+=4){
        fprintf(stdout, "%i ", pixels[b].r);
        fprintf(stdout, "%i ", pixels[b].g);
        fprintf(stdout, "%i\n", pixels[b].b);
    }
}

主函数

#include"defs.h"

int main (){

    //declaring header struct
    info_t headerInfo;
    
    //function to get header
    headerInfo = getHeader();

    int max = (headerInfo.width)*(headerInfo.height);
    int max2 = max*3;

    rgb_t *pixels;

    pixels = (rgb_t *) malloc(max2 * sizeof(int));


    //function to fill array
    fillImageArray(pixels, max);

    writeHeader(headerInfo);    

    //function to print image
    halfSizeWritePixels(pixels, max);

    free(pixels);
    
//end of program
return 0;
}

当前问题

我的思路是读取所有像素后,每4个像素输出一个(因总像素数需变为原有的1/4),但运行后输出的是裁剪效果,而非整体缩放。尝试修改halfSizeWritePixels函数的循环逻辑,但均未得到正确的缩放效果,希望得到技术指导。

内容的提问来源于stack exchange,提问作者o.james

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.12 22:55:17