final_bmp/test/Image.cpp

71 lines
1.7 KiB
C++

#include "Image.h"
#include <iostream>
#include <fstream>
#include <windows.h>
Color::Color()
: r(0),g(0),b(0)
{
}
Color::Color(float r, float g, float b)
: r(r),g(g),b(b)
{
}
Color::~Color(){}
Image::Image(int width, int height)
: m_width(width), m_height(height), m_colors(std::vector<Color>(width * height))
{}
Image::~Image(){}
Color Image::GetColor(int x, int y) const{
return m_colors[y * m_width + x];
}
void Image::SetColor(const Color& color, int x, int y){
m_colors[y * m_width + x].r = color.r;
m_colors[y * m_width + x].g = color.g;
m_colors[y * m_width + x].b = color.b;
}
void Image::Export(const char* path) const{
std::ofstream f;
f.open(path, std::ios::out | std::ios::binary);
if (!f.is_open()){
std::cout << "Error\n";
return;
}
unsigned char bmpPad[3] = {0, 0, 0};
const int paddingAmount = ((4 - (m_width * 3) % 4) % 4);
BITMAPFILEHEADER file_h;
BITMAPINFOHEADER info_h;
const int fileHeaderSize = 14;
const int inforationHeaderSize = 40;
const int fileSize = fileHeaderSize + inforationHeaderSize + m_width * m_height * 3 + paddingAmount * m_height;
f.write((char*)&file_h, fileHeaderSize);
f.write((char*)&info_h, inforationHeaderSize);
for(int y = 0; y < m_height; y++){
for(int x = 0; x < m_width; x++){
unsigned char r = (unsigned char)(GetColor(x, y).r * 255.0f);
unsigned char g = (unsigned char)(GetColor(x, y).g * 255.0f);
unsigned char b = (unsigned char)(GetColor(x, y).b * 255.0f);
unsigned char color[] = {b, g, r};
f.write((char*)color, 3);
}
f.write((char*)bmpPad, paddingAmount);
}
f.close();
std::cout << "done";
}