p.s.需要stb_image.h,可在github下载 p.s.因为未知原因,写到文件里去后所占内存会增大 p.s.写得不咋地
#ifndef _TEXTURE_HPP_
#define _TEXTURE_HPP_
#include <GLES3/gl3.h>
#include <vector>
#include <fstream>
#include <sstream>
#define STB_IMAGE_IMPLEMENTATION
#include "../stb/stb_image.h"
struct GLTexture
{
public:
int w = 0;
int h = 0;
GLenum min_filter = GL_NEAREST;
GLenum mag_filter = GL_NEAREST;
std::vector<GLubyte> pixels;
public:
static GLTexture loadGLTFromFile(std::string path)
{
GLTexture result;
std::ifstream fin;
fin.open(path,std::ios::binary);
fin.read((char*)&result.w,sizeof(int));
fin.read((char*)&result.h,sizeof(int));
fin.read((char*)&result.min_filter,sizeof(GLenum));
fin.read((char*)&result.mag_filter,sizeof(GLenum));
while(!fin.eof())
{
GLubyte pixel;
fin.read((char*)&pixel,sizeof(GLubyte));
result.pixels.push_back(pixel);
}
fin.close();
return result;
}
static void writeToFile(GLTexture texture,std::string path)
{
std::ofstream fout;
fout.open(path,std::ios::binary);
fout.write((char*)&texture.w,sizeof(int));
fout.write((char*)&texture.h,sizeof(int));
fout.write((char*)&texture.min_filter,sizeof(GLenum));
fout.write((char*)&texture.mag_filter,sizeof(GLenum));
for(auto i : texture.pixels)
{
fout.write((char*)&i,sizeof(GLubyte));
}
fout.close();
}
static GLuint toTexture(GLTexture texture,GLenum color_type = GL_RGB,GLenum type = GL_TEXTURE_2D)
{
GLuint id;
glGenTextures(1,&id);
glBindTexture(type,id);
glTexImage2D(type,0,color_type,texture.w,texture.h,0,color_type,GL_UNSIGNED_BYTE,texture.pixels.data());
glTexParameteri(type,GL_TEXTURE_MIN_FILTER,texture.min_filter);
glTexParameteri(type,GL_TEXTURE_MAG_FILTER,texture.mag_filter);
}
static GLTexture toGLTexture(int w,int h,GLubyte* pixels)
{
GLTexture texture;
texture.w = w;
texture.h = h;
for(int i = 0;i < w * h;i++)
{
texture.pixels.push_back(pixels[i]);
}
return texture;
}
static GLTexture loadPixelsFromFile(std::string path)
{
int w,h,nrc;
GLubyte * pixels = stbi_load(path.data(),&w,&h,&nrc,0);
return GLTexture::toGLTexture(w,h,pixels);
}
};
#endif
|