23 static std::vector<unsigned char>
loadImage(
const char* filename,
int& width,
int& height,
int& channels) {
24 std::ifstream file(filename, std::ios::ate | std::ios::binary);
26 if (!file.is_open()) {
27 std::cerr <<
"Error opening file: " << filename << std::endl;
31 size_t fileSize =
static_cast<size_t>(file.tellg());
34 std::vector<unsigned char> buffer(fileSize);
35 file.read(
reinterpret_cast<char*
>(buffer.data()), fileSize);
37 if (buffer.size() >= 54 && buffer[0] ==
'B' && buffer[1] ==
'M') {
38 width = *
reinterpret_cast<int*
>(&buffer[18]);
39 height = *
reinterpret_cast<int*
>(&buffer[22]);
40 channels = *
reinterpret_cast<short*
>(&buffer[28]);
42 if (channels == 24 || channels == 32) {
43 int bytesPerPixel = channels / 8;
44 int padding = (4 - (width * bytesPerPixel) % 4) % 4;
46 std::vector<unsigned char> newBuffer(width * height * 4);
48 for (
int i = 0; i < height; ++i) {
49 for (
int j = 0; j < width; ++j) {
50 int inputIndex = (height - i - 1) * (width * bytesPerPixel + padding) + j * bytesPerPixel;
51 int outputIndex = i * width + j;
53 newBuffer[outputIndex * 4] = buffer[inputIndex + 2];
54 newBuffer[outputIndex * 4 + 1] = buffer[inputIndex + 1];
55 newBuffer[outputIndex * 4 + 2] = buffer[inputIndex];
56 newBuffer[outputIndex * 4 + 3] = (channels == 24) ? 255 : buffer[inputIndex + 3];
60 buffer = std::move(newBuffer);
63 throw std::runtime_error(
"Unsupported image channel count. Only 24-bit and 32-bit images are supported.");
66 throw std::runtime_error(
"Unsupported image format. Only BMP is supported.");