Read/Write to PPM Image File C++

后端 未结 1 1769
隐瞒了意图╮
隐瞒了意图╮ 2021-01-13 18:16

Trying to read and write to/from a PPM Image file (.ppm) in the only way I know how:

std::istream& operator >>(std::istream &inputStream, PPMOb         


        
相关标签:
1条回答
  • 2021-01-13 18:50

    Based on http://fr.wikipedia.org/wiki/Portable_pixmap, P6 is a binary image. This reads a single image. Note that no checking is performed. This needs to be added.

    std::istream& operator >>(std::istream &inputStream, PPMObject &other)
    {
        inputStream >> other.magicNum;
        inputStream >> other.width >> other.height >> other.maxColVal;
        inputStream.get(); // skip the trailing white space
        size_t size = other.width * other.height * 3;
        other.m_Ptr = new char[size];
        inputStream.read(other.m_Ptr, size);
        return inputStream;
    }
    

    This code writes a single image.

    std::ostream& operator <<(std::ostream &outputStream, const PPMObject &other)
    {
        outputStream << "P6"     << "\n"
            << other.width       << " "
            << other.height      << "\n"
            << other.maxColVal   << "\n"
           ;
        size_t size = other.width * other.height * 3;
        outputStream.write(other.m_Ptr, size);
        return outputStream;
    }
    

    m_Ptr contains only the RGB pixel values.

    I tested the code on an image I downloaded from the web (http://igm.univ-mlv.fr/~incerti/IMAGES/COLOR/Aerial.512.ppm) and using the following structure PPMObject it worked.

    struct PPMObject
    {
      std::string magicNum;
      int width, height, maxColVal;
      char * m_Ptr;
    };
    
    0 讨论(0)
提交回复
热议问题