怎么读取PPM文件

janein1 2007-06-15 02:50:00
现在需要把PPM的图像数据读出来处理,怎么读,里面全是乱码。
...全文
2945 7 打赏 收藏 转发到动态 举报
写回复
用AI写文章
7 条回复
切换为时间正序
请发表友善的回复…
发表回复
Inhibitory 2007-06-15
  • 打赏
  • 举报
回复
以前写过,正好手里有:
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

星羽 2007-06-15
  • 打赏
  • 举报
回复
http://vastskysun.bokee.com/viewdiary.14785749.html

CathySun118 2007-06-15
  • 打赏
  • 举报
回复
这里有:http://topic.csdn.net/t/20050912/10/4263160.html
lidongri 2007-06-15
  • 打赏
  • 举报
回复
只要把它的文件结构搞明白就没问题了
  • 打赏
  • 举报
回复
找找PPM的文件格式是什么
sms88 2007-06-15
  • 打赏
  • 举报
回复
需要按他的文件格式来读
aug_eight 2007-06-15
  • 打赏
  • 举报
回复
在百度里搜搜.

65,179

社区成员

发帖
与我相关
我的任务
社区描述
C++ 语言相关问题讨论,技术干货分享,前沿动态等
c++ 技术论坛(原bbs)
社区管理员
  • C++ 语言社区
  • encoderlee
  • paschen
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
  1. 请不要发布与C++技术无关的贴子
  2. 请不要发布与技术无关的招聘、广告的帖子
  3. 请尽可能的描述清楚你的问题,如果涉及到代码请尽可能的格式化一下

试试用AI创作助手写篇文章吧