如何读取图片?

概述:使用stb_image.h头文件开源库,加载图片用;加载图片后保存长宽与像素RGBA

image.h

#pragma once
#include "../global/base.h"

class Image {
public:
Image(const uint32_t& width = 0, const uint32_t& height = 0, RGBA* data = nullptr);
~Image();

static Image* createImage(const std::string& path);
static void destroyImage(Image* image);

public:
uint32_t mWidth{ 0 };
uint32_t mHeight{ 0 };
RGBA* mData{ nullptr };
};

image.cpp

#define STB_IMAGE_IMPLEMENTATION
#include"stb_image.h"
#include "image.h"

Image::Image(const uint32_t& width, const uint32_t& height, RGBA* data) {
mWidth = width;
mHeight = height;
if (data) {
mData = new RGBA[mWidth * mHeight];
memcpy(mData, data, sizeof(RGBA) * mWidth * mHeight);
}
}

Image::~Image() {
if (mData != nullptr) {
delete[] mData;
}
}

Image* Image::createImage(const std::string& path) {
int picType = 0;
int width{ 0 }, height{ 0 };

//stbimage读入的图片,原点在左上角,y轴是向下生长的
//我方图形程序认为,图片应该是左下角为0,0;故需要翻转y轴
stbi_set_flip_vertically_on_load(true);

//由于我们是BGRA的格式,图片是RGBA的格式,所以得交换下R&B
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;
}
}

如何显示图片?

概述:将图片RGBA通过GDI显示

void GPU::drawImage(const Image* image) {
for (uint32_t i = 0; i < image->mWidth; ++i) {
for (uint32_t j = 0; j < image->mHeight; ++j) {
drawPoint(i, j, image->mData[j * image->mWidth + i]);//函数实现见03-构建绘图模拟GPU类
}
}
}

下载 stb_image.h