将pbm ascii保存到pbm二进制c ++

编程入门 行业动态 更新时间:2024-10-28 05:25:31
本文介绍了将pbm ascii保存到pbm二进制c ++的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我有档案pbm P1(ascii)

I have file pbm P1 (ascii)

P1 #Created by Venom 2 2 1 0 0 1

我想将它转换为P4 pbm二进制)。我可以怎么做?

And I want to convert it as P4 (pbm binary). How I can do this?

我有一个像素数组int

i have pixel array of int

int pixel[HEIGHT][WIDTH];

我需要将其转换为二进制数组

I need convert it to binary array here

for (int i =0; i < HEIGHT ; i++) { for (int j =0; j < WIDTH; j++) { } }

推荐答案

这似乎对我能够找到的文件工作,以测试它。

This seems to work for the files I was able to find to test it with.

#include <iostream> #include <fstream> #include <string> #include <vector> struct PBM { unsigned int width; unsigned int height; std::string comment; std::vector<std::vector<char>> data; bool ReadAscii(std::ifstream& f) { std::string id; if(!std::getline(f, id) || id != "P1") { return false; } if(f.peek() == '#' && !std::getline(f, comment)) { return false; } if(!(f >> width >> height)) { return false; } data.resize(height); int temp; for(size_t y = 0; y < data.size(); ++y) { data[y].resize(width); for(size_t x = 0; x < width; ++x) { if(!(f >> temp)) { return false; } data[y][x] = static_cast<char>(temp); } } return true; } bool WriteBinary(std::ofstream& f) { if(!(f << "P4\n")) { return false; } if(!comment.empty() && !(f << comment << "\n")) { return false; } if(!(f << width << " " << height << "\n")) { return false; } std::vector<char> linebits((width + (CHAR_BIT - 1)) / CHAR_BIT); for(size_t y = 0; y < data.size(); ++y) { std::fill(linebits.begin(), linebits.end(), 0); for(size_t x = 0; x < width; ++x) { const int byte_pos = x / CHAR_BIT; const int bit_pos = (CHAR_BIT - 1) - (x % CHAR_BIT); linebits[byte_pos] |= (data[y][x] << bit_pos); } if(!f.write(&linebits[0], linebits.size())) { return false; } } return true; } }; int main(int argc, char * argv[]) { if(argc != 3) { std::cerr << "Usage: convertpbm <ascii filename> <binary filename>\n"; return 0; } PBM pbm; std::ifstream inFile(argv[1]); if(!inFile) { std::cerr << "Could not open '" << argv[1] << "' for input!\n"; return 0; } if(!pbm.ReadAscii(inFile)) { std::cerr << "Error reading input file!\n"; } std::ofstream outFile(argv[2], std::ios::binary); if(!outFile) { std::cerr << "Could not open '" << argv[1] << "' for output!\n"; return 0; } if(!pbm.WriteBinary(outFile)) { std::cerr << "Error writing output file!\n"; } return 0; }

更多推荐

将pbm ascii保存到pbm二进制c ++

本文发布于:2023-10-30 01:23:07,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1541349.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:pbm   ascii

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!