57 lines
1.2 KiB
C++
57 lines
1.2 KiB
C++
#define STB_IMAGE_IMPLEMENTATION
|
||
#include"stb_image.h"
|
||
#include "image.h"
|
||
|
||
Image::Image(const int& width, const int& height, RGBA* data) {
|
||
m_width = width;
|
||
m_height = height;
|
||
if (data) {
|
||
m_data = new RGBA[m_width * m_height];
|
||
memcpy(m_data, data, sizeof(RGBA) * m_width * m_height);
|
||
}
|
||
}
|
||
|
||
Image::~Image() {
|
||
if (m_data != nullptr) {
|
||
delete[] m_data;
|
||
}
|
||
}
|
||
|
||
//仅接收(-1,1)的参数
|
||
RGBA Image::GetColor(const float& p_u, const float& p_v)
|
||
{
|
||
if (!m_data) { return RGBA(255,255,255,255); }
|
||
/*此处注意截断误差,不要直接算index,一定要让x和y分别截断一下*/
|
||
int x = fmod(p_u + 1, 1.f) * m_width;
|
||
int y = fmod(p_v + 1, 1.f) * m_height;
|
||
return m_data[x + y * m_width];
|
||
}
|
||
|
||
Image* Image::CreateImage(const std::string& path) {
|
||
int picType = 0;
|
||
int width{ 0 }, height{ 0 };
|
||
|
||
stbi_set_flip_vertically_on_load(true);
|
||
|
||
unsigned char* bits = stbi_load(path.c_str(), &width, &height, &picType, STBI_rgb_alpha);
|
||
for (int i = 0; i < width * height * 4; i += 4)
|
||
{
|
||
BYTE tmp = bits[i];
|
||
bits[i] = bits[i + 2];
|
||
bits[i + 2] = tmp;
|
||
}
|
||
|
||
Image* image = new Image(width, height, (RGBA*)bits);
|
||
|
||
stbi_image_free(bits);
|
||
|
||
return image;
|
||
|
||
}
|
||
|
||
void Image::DestroyImage(Image* image) {
|
||
if (image) {
|
||
delete image;
|
||
}
|
||
}
|