bmp image to matrix (2d array) in c -
i need put bmp (rgb 24 bit) image 2d array, using c language. have written functions, functions work square images. have created structure store pixels:
typedef struct{ int red; int green; int blue; }pixel; i have created 2 int extern values y , x store height , width of image. code (i omitted setwidthheight , createnewimage functions because i'm sure work)
int x, y; int bitmapin(file* fp,/* int height, int width, */ pixel** img1){ long n; int t; fseek(fp, 10, seek_set); fread(&t, 1, 4, fp); //reads offset , puts in t fseek(fp, t, seek_set); int i, p, e; e=4-((x*3)%4); if (e==4) { e=0; } (i=y-1; i>=0; i-- ) { (p=0; p<x; p++) { n=fread(&img1[i][p].blue, 1, 1, fp); if (n!=1) { return 29; } n=fread(&img1[i][p].green, 1, 1, fp); if (n!=1) { return 30; } n=fread(&img1[i][p].red, 1, 1, fp); if (n!=1) { return 31; } } fseek(fp, e, seek_cur); } return 0; } pixel** make2dpixelarray(/*int y, int x*/){ pixel** thearray; thearray=(pixel**) malloc(x*sizeof(pixel*)); (int i=0; i<x; i++) { thearray[i]=(pixel*) malloc(y*sizeof(pixel)); } return thearray; } int main(int argc, const char * argv[]) { file* fp; fp=fopen("/users/admin/desktop/immagine5.bmp", "r"); if (fp==null) { return 20; } setwidthheight(fp); //puts x=width , y=height, works pixel** img1=make2dpixelarray(); //creates 2d pixel array , memory bitmapin(fp, img1); //this function should put values of rgb pixel matrix createnewimage(fp, img1); //this function creates new image. return 0; } when image square there no problems when:
- height>width: error "bad_access..." when try read first pixel in bitmapin()
- width>height: first line of pixel ok. left side kind of copy of right side more blue , little green.
could me solving problem?
you've got x , y swapped when fread values array. think. it's not i've tested out or anything. way lazy that.
for (i=y-1; i>=0; i-- ) { (p=0; p<x; p++) { n=fread(&img1[i][p].blue i walks through y , p walks through x.
when malloc it, set img[x][y]
thearray=(pixel**) malloc(x*sizeof(pixel*)); (int i=0; i<x; i++) { thearray[i]=(pixel*) malloc(y*sizeof(pixel)); general advice: stay away globals, i'd pass in variables have commented out. name variables better t , e. return 29,30,31 values? try enum or #defines names. (and ignore return value afterwards)
the biggest reason bug wasn't apparent naming scheme. , p? come on, pass in sizex, , sizey, , have x , y worker variables. if context wasn't bitmapin(), variables should bitmapsizex. naming important yo.
Comments
Post a Comment