-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbmp_output.cpp
More file actions
70 lines (59 loc) · 2.66 KB
/
Copy pathbmp_output.cpp
File metadata and controls
70 lines (59 loc) · 2.66 KB
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
#include "bmp_output.h"
#include <cmath>
#include <vector>
#include <string>
#include <fstream>
#include "vector.h"
void saveBMP(const std::string& filename, int width, int height, const std::vector<Vector3>& framebuffer) {
// BMP requires row padding to a multiple of 4 bytes
int rowStride = width * 3;
int padding = (4 - (rowStride % 4)) % 4;
int fileSize = 54 + (rowStride + padding) * height;
unsigned char header[54] = {
// Bitmap file header (14 bytes)
'B', 'M', // Signature
0,0,0,0, // File size (will fill below)
0,0, 0,0, // Reserved
54,0,0,0, // Pixel data offset
// DIB header (BITMAPINFOHEADER — 40 bytes)
40,0,0,0, // Header size
0,0,0,0, // Width (will fill below)
0,0,0,0, // Height (will fill below)
1,0, // Planes
24,0, // 24 bits per pixel
0,0,0,0, // Compression (0 = none)
0,0,0,0, // Image size (ignored for uncompressed)
0,0,0,0, // X pixels per meter
0,0,0,0, // Y pixels per meter
0,0,0,0, // Colors in color table
0,0,0,0 // Important colors
};
// Fill dynamic parts of header
header[ 2] = (unsigned char)(fileSize );
header[ 3] = (unsigned char)(fileSize >> 8);
header[ 4] = (unsigned char)(fileSize >> 16);
header[ 5] = (unsigned char)(fileSize >> 24);
header[18] = (unsigned char)(width );
header[19] = (unsigned char)(width >> 8);
header[20] = (unsigned char)(width >> 16);
header[21] = (unsigned char)(width >> 24);
header[22] = (unsigned char)(height );
header[23] = (unsigned char)(height >> 8);
header[24] = (unsigned char)(height >> 16);
header[25] = (unsigned char)(height >> 24);
std::ofstream out(filename, std::ios::binary);
out.write((char*)header, 54);
unsigned char pad[3] = {0, 0, 0};
// BMP stores scanlines bottom → top
for (int y = height - 1; y >= 0; --y) {
for (int x = 0; x < width; ++x) {
const Vector3& c = framebuffer[y * width + x];
unsigned char r = (unsigned char)(std::min(1.0f, c.x) * 255.0f);
unsigned char g = (unsigned char)(std::min(1.0f, c.y) * 255.0f);
unsigned char b = (unsigned char)(std::min(1.0f, c.z) * 255.0f);
unsigned char pixel[3] = { b, g, r }; // BMP is BGR
out.write((char*)pixel, 3);
}
out.write((char*)pad, padding); // Row padding
}
}