从矢量写入 PGM 文件<unsigned char>

Writing a PGM file from a vector<unsigned char>

我正在编写一个程序来操作 PGM 文件,方法是获取输入 PGM,将数据存储在 vector<unsigned char> 中,使用数据向量创建新向量等等,直到我使用创建输出 PGM 文件的最后一个向量。

我一直一步一个脚印,我先是把输入的PGM放到一个vector<unsigned char>,然后把原始向量输出到一个新的PGM文件。基本上,将输入复制到一个新文件中。它不起作用,我不确定为什么。

这是我的代码:

//note: int degree is for after I start manipulating the data and dimensions will change
void outputFile(vector<unsigned char> image, int degree, int original_r, int original_c){
FILE* pgmimg;
pgmimg = fopen("pgmimg.PGM", "wb");
int temp;

int width = static_cast<int>(original_c / (pow(2, degree)));
int height = static_cast<int>(original_r / (pow(2, degree)));

fprintf(pgmimg, "P2\n");
fprintf(pgmimg, "%d %d\n", width, height);
fprintf(pgmimg, "255\n");

for (int i = 0; i < height; i++){
    for (int k = 0; k < width; k++){
        temp = image[(i*width)+k];
        
        fprintf(pgmimg, "%d ", temp);
    }
    fprintf(pgmimg, "\n");
}
fclose(pgmimg);}

int main(){
// PATH_NAME is a string defined at the beginning of the code set to the path to the input image
fstream img;
img.open(PATH_NAME, ios::in | ios::binary | ios::out);

string line;
getline(img, line);
if(!img.is_open()){
    cout << "Unable to open image" << endl;
    return 0;
}
if(!line.compare("P2")){
    cout << "Incorrect file format" << endl;
    return 0;
}

getline(img, line);
istringstream iss(line);
string row_string, col_string;
iss >> col_string;
iss >> row_string;

int original_rows = stoi(row_string);
int original_cols = stoi(col_string);

cout << original_rows << " " << original_cols << endl;
getline(img, line); //get max value

//collect data from input
int length = img.tellg();
char* buffer = new char [length];
img.read (buffer, length);
//copy data into original
vector<unsigned char> original(original_rows*original_cols);
for(int i = 0; i < original.size(); i++){
    original[i] = buffer[i];
}
outputFile(original, 0, original_rows, original_cols);
img.close();
return 0;
}

这是我输入的内容(Whosebug 不允许我输入 PGM,所以这是 PNG 版本):

这是在“pgmimg.PGM”中输出的内容:

显然,完全错误(正确的尺寸,错误的一切)。任何人都可以帮助我或让我知道读取输入或写入输出是否有问题?谢谢。

输入的代码看起来不对

int length = img.tellg();
char* buffer = new char [length];
img.read (buffer, length);

tellg 是文件中的当前位置。这与要读取的数据量无关。只需将数据直接读入向量

vector<unsigned char> original(original_rows*original_cols);
img.read(original.data(), original.size());