0

我正在为基本的简历想法编写一个简单的 PGM 文件阅读器,但我遇到了一个奇怪的问题。我的方法似乎适用于对称文件(例如 255 x 255),但是当我尝试读取非对称文件(300 x 246)时,我得到了一些奇怪的输入。一个文件读取到某个点,然后将 ESCAPE 字符(ASCII 27)转储到图像的其余部分(见下文),而其他文件则不会读取。我认为这可能是一些有缺陷的逻辑或内存问题。任何帮助,将不胜感激。

在此处输入图像描述在此处输入图像描述

        // Process files of binary type (P5)
    else if(holdString[1] == '5') {
        // Assign fileType value
        fileType = 5;

        // Read in comments and discard
        getline(fileIN, holdString);

        // Read in image Width value
        fileIN >> width;

        // Read in image Height value
        fileIN >> height;

        // Read in Maximum Grayscale Value
        fileIN >> max;

        // Determine byte size if Maximum value is over 256 (1 byte)
        if(max < 256) {
            // Collection variable for bytes
            char readChar;

            // Assign image dynamic memory
            *image = new int*[height];
            for(int index = 0; index < height; index++) {
                (*image)[index] = new int[width];
            }

            // Read in 1 byte at a time
            for(int row = 0; row < height; row++) {
                for(int column = 0; column < width; column++) {
                    fileIN.get(readChar);
                    (*image)[row][column] = (int) readChar;
                }
            }

            // Close the file
            fileIN.close();
        } else {
            // Assign image dynamic memory
            // Read in 2 bytes at a time
            // Close the file
        }
    }
4

1 回答 1

0

稍微修改了一下,并想出了至少大部分的解决方案。使用 .read() 函数,我能够绘制整个文件,然后将其逐个读取到 int 数组中。我保留了动态内存,因为我想绘制不同大小的文件,但我确实更关注它是如何读入数组的,所以谢谢你的建议,马克。编辑似乎适用于高达 1000 像素宽或高的文件,这对于我使用它的目的来说很好。之后,它会扭曲,但我仍然会接管它而不读取文件。

            if(max < 256) {
            // Collection variable for bytes
            int size = height * width;
            unsigned char* data = new unsigned char[size];

            // Assign image dynamic memory
            *image = new int*[height];
            for(int index = 0; index < height; index++) {
                (*image)[index] = new int[width];
            }

            // Read in 1 byte at a time
            fileIN.read(reinterpret_cast<char*>(data), size * sizeof(unsigned char));

            // Close the file
            fileIN.close();

            // Set data to the image
            for(int row = 0; row < height; row++) {
                for(int column = 0; column < width; column++) {
                    (*image)[row][column] = (int) data[row*width+column];
                }
            }

            // Delete temporary memory
            delete[] data;
        }
于 2015-08-05T04:32:27.283 回答