简体   繁体   中英

Copy an image bit by bit C++

I recently found some documentation on file open modes in C++ and, using ios_base::binary , tried to open an image (.JPG), read the bits one by one, and write them in a separate file ( ofstream ) with a.JPG extension. The problem is that I get an error when trying to open the newly created image: Error interpreting JPEG file . Any help?

code:

int main()
{
    char a;
    std::ifstream fin {"image.jpg", std::ios_base::binary};
    std::ofstream fout {"uzicopied.jpg", std::ios_base::binary};
    while (true)
    {
        if (!(fin >> a) || !fin) break;
        fout << a;
    }
    return 0;
}

fin >> a skips whitespace, even if the file is opened in binary mode. Use get instead. You can also simplify your while loop.

char a;
while (fin.get(a))
    fout.put(a);   // fout << a; would also work

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM