将pbm ascii保存到pbm二进制c ++ [英] Save pbm ascii to pbm binary c++
本文介绍了将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 ++的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文