[C++] [OpenGL ES 3.0] 写了个GLTexture

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);
		return id;
	}
	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
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值