在C语言中,可以使用OpenGL库读取JPG纹理。以下是一个简单的示例代码:
#include <GL/glut.h>
#include <jpeglib.h>
#include <jerror.h>
// 读取JPG图像并返回纹理ID
GLuint loadJPGTexture(const char *filename) {
struct jpeg_decompress_struct cinfo;
struct jpeg_error_mgr jerr;
FILE *infile;
JSAMPARRAY buffer;
int row_stride;
GLuint texture;
// 打开文件
infile = fopen(filename, "rb");
if (infile == NULL) {
printf("Error opening JPEG file %s\n", filename);
return 0;
}
// 初始化JPEG解压结构
cinfo.err = jpeg_std_error(&jerr);
jpeg_create_decompress(&cinfo);
jpeg_stdio_src(&cinfo, infile);
jpeg_read_header(&cinfo, TRUE);
// 获取图像尺寸
int width = cinfo.image_width;
int height = cinfo.image_height;
// 设置解压参数
jpeg_start_decompress(&cinfo);
row_stride = cinfo.output_width * cinfo.output_components;
// 分配内存
buffer = (*cinfo.mem->alloc_sarray) ((j_common_ptr) &cinfo, JPOOL_IMAGE, row_stride, 1);
// 读取图像数据
unsigned char *image_data = (unsigned char *) malloc(width * height * 3);
int row = 0;
while (cinfo.output_scanline < cinfo.output_height) {
jpeg_read_scanlines(&cinfo, buffer, 1);
memcpy(image_data + row * width * 3, buffer[0], row_stride);
row++;
}
// 结束解压
jpeg_finish_decompress(&cinfo);
jpeg_destroy_decompress(&cinfo);
fclose(infile);
// 创建纹理
glGenTextures(1, &texture);
glBindTexture(GL_TEXTURE_2D, texture);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, width, height, 0, GL_RGB, GL_UNSIGNED_BYTE, image_data);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
// 释放内存
free(image_data);
return texture;
}
在这个示例中,我们使用了JPEG库来读取JPG图像,并将其转换为OpenGL纹理。你可以使用这个函数来加载JPG纹理,并将其应用到OpenGL对象上。
领取专属 10元无门槛券
手把手带您无忧上云