怎么读取PPM文件
现在需要把PPM的图像数据读出来处理,怎么读,里面全是乱码。
[解决办法]
这里有:http://topic.csdn.net/t/20050912/10/4263160.html
[解决办法]
以前写过,正好手里有:
PPM的图像数据是按BGR格式存储,当使用的格式是RGB时,要交换B和G,如在OpenGL中默认的就是RGB。
#ifndef _TGALOAD_H_
#define _TGALOAD_H_
#include <stdio.h>
typedef struct {
GLubyte* data;
GLuint width;
GLuint height;
GLuint rgbType;
} TextureImage;
GLboolean loadTGA(char* fileName, TextureImage* textureImage) {
GLubyte TGAheader[12]= { 0, 0, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; // 无压缩的TGA文件头
GLubyte TGAcompare[12]; // 保存读入的文件头信息
GLubyte header[6]; // 保存最有用的图像信息,宽,高,位深
GLuint bytesPerPixel; // 记录每个颜色所占用的字节数
GLuint imageSize; // 记录文件大小
GLuint temp; // 临时变量
FILE *file = fopen(fileName, "rb "); // 打开一个TGA文件
if (file==NULL || // 文件存在么?
fread(TGAcompare, 1, sizeof(TGAcompare), file)!= sizeof(TGAcompare) || // 是否包含12个字节的文件头?
memcmp(TGAheader, TGAcompare, sizeof(TGAheader))!= 0 || // 是否是我们需要的格式?
fread(header, 1, sizeof(header), file)!= sizeof(header)) { // 如果是读取下面六个图像信息
if (file == NULL) // 文件不存在返回错误
return false;
else {
fclose(file); // 关闭文件返回错误
return false;
}
}
textureImage-> width = header[1] * 256 + header[0]; // 记录文件宽度
textureImage-> height = header[3] * 256 + header[2]; // 记录文件高度
if (textureImage-> width <= 0 || // 宽度是否小于0
textureImage-> height <= 0 || // 高度是否小于0
(header[4] != 24 && header[4] != 32)) { // TGA文件是24/32位?
fclose(file); // 如果失败关闭文件,返回错误
return false;
}
bytesPerPixel = header[4] > > 3; // 记录每个象素所占的字节数
textureImage-> rgbType = bytesPerPixel; // 记录每个象素所占的字节数
imageSize = textureImage-> width *textureImage-> height * bytesPerPixel; // 计算TGA文件加载所需要的内存大小
textureImage-> data = (GLubyte*)malloc(imageSize); // 分配内存去保存TGA数据
if (textureImage-> data == NULL || // 系统是否分配了足够的内存?
fread(textureImage-> data, 1, imageSize, file)!= imageSize) { // 是否成功读入内存?
if (textureImage-> data != NULL) { // 是否有数据被加载
free(textureImage-> data); // 如果是,则释放载入的数据
}
fclose(file); // 关闭文件
return false; // 返回错误
}
for (GLuint i=0; i <GLuint(imageSize); i+=bytesPerPixel) { // 循环所有的像素
// 交换R和B的值
temp = textureImage-> data[i];
textureImage-> data[i] = textureImage-> data[i + 2];
textureImage-> data[i + 2] = temp;
}
fclose(file); // 关闭文件
return true;
}
#endif