-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbmp.c
106 lines (106 loc) · 2.27 KB
/
bmp.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
#include <stdio.h>
#include <stdlib.h>
#include <sys/malloc.h>
typedef unsigned long DWORD;
typedef int BOOL;
typedef unsigned char BYTE;
typedef unsigned short WORD;
typedef struct tagBITMAPINFOHEADER
{
DWORD biSize;
long biWidth;
long biHeight;
WORD biPlanes;
WORD biBitCount;
DWORD biCompression;
DWORD biSizeImage;
long biXPelsPerMeter;
long biYPelsPerMeter;
DWORD biClrUsed;
DWORD biClrImportant;
} BITMAPINFOHEADER;
int ReadBmp(const char *szFileName);
int GetDIBColor(int X, int Y, BYTE *r, BYTE *g, BYTE *b);
BITMAPINFOHEADER bih;
BYTE *Buffer = NULL;
long LineByteWidth;
int main(void)
{
int x, y;
BYTE r, g, b;
int n;
char szfilename[255] = "diablo3_pose_diffuse.bmp";
if (ReadBmp(szfilename) == 0)
{
printf("failure to read file %s", szfilename);
return 1;
}
printf("Width: %ld\n", bih.biWidth);
printf("Height: %ld\n", bih.biHeight);
printf("BitCount: %d\n\n", (int)bih.biBitCount);
while (1)
{
printf("input the X:");
scanf("%d", &x);
if (x < 0)
break;
printf("input the Y:");
scanf("%d", &y);
if (GetDIBColor(x, y, &r, &g, &b) == 1)
printf("(%d, %d): r:%d, g:%d, b:%d\n", x, y, (int)r, (int)g, (int)b);
else
printf("input error.\n");
}
free(Buffer);
return 0;
}
int ReadBmp(const char *szFileName)
{
FILE *file;
WORD bfh[7];
long dpixeladd;
if (NULL == (file = fopen(szFileName, "rb")))
{
return 0;
}
printf("%s\n", szFileName);
fread(&bfh, sizeof(WORD), 7, file);
if (bfh[0] != (WORD)(((WORD)'B') | ('M' << 8)))
{
fclose(file);
return 0;
}
fread(&bih, sizeof(BITMAPINFOHEADER), 1, file);
if (bih.biBitCount < 24)
{
fclose(file);
return 0;
}
dpixeladd = bih.biBitCount / 8;
LineByteWidth = bih.biWidth * (dpixeladd);
if ((LineByteWidth % 4) != 0)
LineByteWidth += 4 - (LineByteWidth % 4);
if ((Buffer = (BYTE *)malloc(sizeof(BYTE) * LineByteWidth * bih.biHeight)) != NULL)
{
fread(Buffer, LineByteWidth * bih.biHeight, 1, file);
fclose(file);
return 1;
}
fclose(file);
return 0;
}
int GetDIBColor(int X, int Y, BYTE *r, BYTE *g, BYTE *b)
{
int dpixeladd;
BYTE *ptr;
if (X < 0 || X >= bih.biWidth || Y < 0 || Y >= bih.biHeight)
{
return 0;
}
dpixeladd = bih.biBitCount / 8;
ptr = Buffer + X * dpixeladd + (bih.biHeight - 1 - Y) * LineByteWidth;
*b = *ptr;
*g = *(ptr + 1);
*r = *(ptr + 2);
return 1;
}