-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathBitmap.cpp
90 lines (71 loc) · 2.66 KB
/
Bitmap.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
#include <vector>
#include <fstream>
#include <cstring>
struct Pixel { unsigned char r, g, b; };
void WriteBMP(const char* fname, Pixel* a_pixelData, int width, int height)
{
int paddedsize = (width*height) * sizeof(Pixel);
unsigned char bmpfileheader[14] = {'B','M', 0,0,0,0, 0,0, 0,0, 54,0,0,0};
unsigned char bmpinfoheader[40] = {40,0,0,0, 0,0,0,0, 0,0,0,0, 1,0, 24,0};
bmpfileheader[ 2] = (unsigned char)(paddedsize );
bmpfileheader[ 3] = (unsigned char)(paddedsize>> 8);
bmpfileheader[ 4] = (unsigned char)(paddedsize>>16);
bmpfileheader[ 5] = (unsigned char)(paddedsize>>24);
bmpinfoheader[ 4] = (unsigned char)(width );
bmpinfoheader[ 5] = (unsigned char)(width>> 8);
bmpinfoheader[ 6] = (unsigned char)(width>>16);
bmpinfoheader[ 7] = (unsigned char)(width>>24);
bmpinfoheader[ 8] = (unsigned char)(height );
bmpinfoheader[ 9] = (unsigned char)(height>> 8);
bmpinfoheader[10] = (unsigned char)(height>>16);
bmpinfoheader[11] = (unsigned char)(height>>24);
std::ofstream out(fname, std::ios::out | std::ios::binary);
out.write((const char*)bmpfileheader, 14);
out.write((const char*)bmpinfoheader, 40);
out.write((const char*)a_pixelData, paddedsize);
out.flush();
out.close();
}
void SaveBMP(const char* fname, const unsigned int* pixels, int w, int h)
{
std::vector<Pixel> pixels2(w*h);
for (size_t i = 0; i < pixels2.size(); i++)
{
Pixel px;
px.r = (pixels[i] & 0x00FF0000) >> 16;
px.g = (pixels[i] & 0x0000FF00) >> 8;
px.b = (pixels[i] & 0x000000FF);
pixels2[i] = px;
}
WriteBMP(fname, &pixels2[0], w, h);
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
std::vector<unsigned int> LoadBMP(const char* filename, int* pW, int* pH)
{
FILE* f = fopen(filename, "rb");
if(f == NULL)
{
(*pW) = 0;
(*pH) = 0;
return std::vector<unsigned int>();
}
unsigned char info[54];
fread(info, sizeof(unsigned char), 54, f); // read the 54-byte header
int width = *(int*)&info[18];
int height = *(int*)&info[22];
int row_padded = (width*3 + 3) & (~3);
unsigned char* data = new unsigned char[row_padded];
std::vector<unsigned int> res(width*height);
for(int i = 0; i < height; i++)
{
fread(data, sizeof(unsigned char), row_padded, f);
for(int j = 0; j < width; j++)
res[i*width+j] = (uint32_t(data[j*3+0]) << 16) | (uint32_t(data[j*3+1]) << 8) | (uint32_t(data[j*3+2]) << 0);
}
fclose(f);
delete [] data;
(*pW) = width;
(*pH) = height;
return res;
}