因此,我尝试编写一个程序,该程序将接收PPM图像并制作它的新副本。
我使用平面阵列来保存原始像素数据并使用fwrite
写入新图像。但是,当试图使用“2-D”阵列来实现相同的结果但我不断得到一个seg。错误,我不知道如何解决它。
这些是我的课程:
ppmWriter.cc
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "ppmWriter.h"
int ppmWriter(const char *filename,int **array, int *width, int *height)
{
const int max = *width**height*3;
FILE * fp;
fp = fopen(filename, "w");
fprintf(fp, "P6\n%d %d\n255\n", *width, *height);
unsigned char* rgb;
int *newarray = new int[*width**height*3];
int* flat = array[0];
int nelements = *width**height;
int index=0;
for(int i=0; i<nelements; ++i) // loop for w*h times and each iteration fills in 3 slots-r,g,b- of the
{
rgb = (unsigned char*)(&(flat[i]));
newarray[index++]=rgb[0];
newarray[index++]=rgb[1];
newarray[index++]=rgb[2];
}
fwrite( flat, sizeof(char),max,fp);
fclose(fp);
printf("OK - file %s saved\n", filename);
return 0;
}
Main.cc
#include <cstdio>
#include <stdio.h>
#include "ppmWriter.h"
#include "ppmReader.h"
int main(int argc, char** argv)
{
int width, height;
int ** array = ppmReader("test.ppm",&width,&height);
ppmWriter("test2.ppm", array , &width, &height);
}
ppmReader.cc
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "ppmReader.h"
int **ppmReader( const char *filename, int *width, int *height)
{
FILE *fp = fopen(filename,"r");
unsigned char *buff;
int s,h,w;
if (!fp) {
fprintf(stderr, "Unable to open file '%s'\n", filename);
exit(1);
}
fscanf(fp,"P6\n%d %d\n255\n", &w, &h);
*width=w ;
*height=h;
s= h*w*3;
buff= new unsigned char[s];
fread(buff,sizeof(char),s,fp);
fclose(fp);
// Initiates a Numerical Recepies Trick array ( pointer to a pointer to and int array, aka 2D array)
//-----------------------------------------------------------------------
unsigned char* rgb;
int** array = new int*[w];
*array = new int[w*h];
for(int j=1; j<h; ++j)
{
array[ j ] = array[ j-1] + w;
}
//1-loop traversing through array
//-----------------------------------------------------------------------
int* flat = array[0];
int nelements = w*h;
for(int i=0; i<nelements; ++i)
{
rgb = (unsigned char*)(&(flat[i]));
rgb[i] = *(buff++);
rgb[i+1] = *(buff++);
rgb[i+2] = *(buff++);
rgb[i+3] = 0;
}
return array;
}
头文件:
#ifndef ppmReader_h
#define ppmReader_h
#include <stdio.h>
int **ppmReader( const char *filename, int *width, int *height);
#endif /* ppmReader_h */
和
#ifndef ppmWriter_h
#define ppmWriter_h
#include <stdio.h>
int ppmWriter(const char *filename, int** array, int *width, int *height);
#endif /* ppmWriter_h */
我实际上是将数据分配到一个二维数组中,然后“尝试”恢复此过程并将其写入一个平面数组并将其写入图像。