-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathimage.cpp
109 lines (88 loc) · 2.91 KB
/
image.cpp
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
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
/*
*/
#include <iostream>
#include <fstream>
#include "./header/image.hpp"
//struct definitions
Color::Color()
: r(0), g(0), b(0)
{
}
Color::Color(float r, float g, float b)
: r(r), g(g), b(b)
{
}
// class definitions
Image::Image()
{
}
// Image::Image(int imgWidth, int imgHeight)
// : imgWidth(imgWidth), imgHeight(imgHeight), imgColor(std::vector<Color>(imgWidth * imgHeight))
// {
// }
void Image::readFile(const char* filename)
{
std::ifstream f;
f.open(filename, std::ios::in | std::ios::binary);
//check if the file is open
if(!f.is_open())
{
std::cout << "Couldn't open the file\n";
return;
}
f.read((char*)(fileHeader), sizeof(fileHeader));
f.read((char*)(infoHeader), sizeof(infoHeader));
//first 2 bytes of .bmp should be BM
if(fileHeader[0] != 'B' || fileHeader[1] != 'M')
{
std::cout << "Not a bitmap file\n";
f.close();
return;
}
//from wikipidea (offset of the width and height)
imgWidth = infoHeader[4] + (infoHeader[5] << 8) + (infoHeader[6] << 16) + (infoHeader[7] << 24);
imgHeight = infoHeader[8] + (infoHeader[9] << 8) + (infoHeader[10] << 16) + (infoHeader[11] << 24);
//resizing the color vector
imgColor.resize(imgWidth * imgHeight);
//each row should have bytes divisible by 4 so padding might be added
//width*3 because r, g, b for each pixel
const int paddingAmount = (4 - (imgWidth * 3 % 4)) % 4;
for(int i = 0; i < imgHeight; i++)
{
for(int j = 0; j < imgWidth; j++)
{
unsigned char color[3];
f.read((char*)(color), sizeof(color));
imgColor[imgWidth * i + j].r = (float)color[0] / 255.0f;
imgColor[imgWidth * i + j].g = (float)color[1] / 255.0f;
imgColor[imgWidth * i + j].b = (float)color[2] / 255.0f;
}
//ignores the padding amount at the end of each row
f.ignore(paddingAmount);
}
f.close();
std::cout << "File has been read successfully\n";
}
void Image::flipImage()
{
const int paddingAmount = (4 - (imgWidth * 3 % 4)) % 4;
int padding[] = {0, 0, 0};
std::ofstream f;
f.open("newImage.bmp", std::ios::out | std::ios::binary);
f.write((char*)(fileHeader), sizeof(fileHeader));
f.write((char*)(infoHeader), sizeof(infoHeader));
for(int i = imgHeight-1; i >= 0; i--)
{
for(int j = 0; j < imgWidth; j++)
{
unsigned char color[3];
color[0] = (char)(imgColor[imgWidth * i + j].r * 255.0f);
color[1] = (char)(imgColor[imgWidth * i + j].g * 255.0f);
color[2] = (char)(imgColor[imgWidth * i + j].b * 255.0f);
f.write((char*)(color), sizeof(color));
}
f.write((char*)(padding), paddingAmount);
}
f.close();
std::cout << "Image flip successful\n";
}