1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78
|
void Bitmap::read_file(const char * file_name) {
fstream file(file_name, ios_base::in);
if (file.is_open()) {
string line_one, line_two, line_pixels;
while(getline(file, line_one)) {
if(line_one.at(0) != '#') {
if(line_one == "P1")
this->magicNumber = P1;
else
this->magicNumber = P4;
break;
}
}
while(getline(file, line_two)) {
string width, height;
stringstream ss(line_two);
if(line_two.at(0) != '#') {
if(getline(ss, width, ' '))
this->width = stoi(width);
if(getline(ss, height, ' '))
this->height = stoi(height);
break;
}
}
if(this->magicNumber == P1) {
this->pixels = new Matrix<int>(this->width, this->height);
vector<int> p;
while(getline(file, line_pixels)) {
if(line_pixels.size() > 0 && line_pixels.at(0) != '#') {
string number;
stringstream ss(line_pixels);
while(getline(ss, number, ' ')) {
int data = stoi(number);
p.push_back(data);
}
}
}
int count = 0;
for(int i=0; i<height; i++) {
for(int j=0; j<width; j++) {
this->pixels->set(i, j, p[count++]);
}
}
}
if(this->magicNumber == P4) {
this->pixels = new Matrix<int>(this->width, this->height);
vector<int> p;
int size = width * height;
for(int i=0; i<size; i++) {
char byte[1];
file.read(byte, 1);
unsigned char c = (unsigned char)byte[0];
for(int x=0; x != 8; x++)
p.push_back( (c & (1 << x)) != 0 );
}
int count = 0;
for(int i=0; i<height; i++) {
for(int j=0; j<width; j++) {
this->pixels->set(i, j, p[count++]);
}
}
}
}
file.close();
}
|