본문 바로가기
kxLibrary

KFC1.0 Class Update For KFCBitmap

by 두루물 2011. 5. 5.

KRKIM's Foundation Classes Library(KFC)

Bugfix::
-HPALETTE 형 HANDLE을 delete 한 경우를 DeleteObject()로 해제하도록 함.
-DLL에서 Free()시 오류 문제 해결.

void KFCBitmap::Free()
{
     if (m_hBitmap)
          ::DeleteObject (m_hBitmap);
     m_hBitmap = NULL;

     if(m_pBI)
        delete [] (BYTE*)m_pBI;
     if(m_pPixelBits)
        delete [] m_pPixelBits;
     if(m_hPal)
        //delete m_hPal; //bugfix 2011.05.05
        DeleteObject(m_hPal);
     m_pBI = 0;
     m_pPixelBits = 0;
     m_hPal = 0;
}

Source Code:


/* 
  $Id: KFCBitmap.h 3 2009-12-20 19:12:53Z krkim $ $Revision: 3 $
  $HeadURL: https://krkim-laptop/svn/KFC/trunk/KFCBitmap.h $
 */

/*
/* W E L C O M E    T O    'K  F  C  W  N  D' 
 *                                 S I M P L E    W I N D O W   L I B R A R Y 
 * KFC - K)RKIM's F)oundation C)lasses Library for MS-Windows SDK Platform.
 *       IT IS FOR SDK CLASSES NOT MFC!!
 * Author: K.R Kim (Kyeong Rae Kim) / Korea.
 * E-mail: Quasar@hitel.net / http://www.kebi.com/~netzip (defuncted)
 * This library is for simple and light build and running without many MFC DLLs.
 * version: 1.0    2000/01/07
 * purpose: like-as MFC interface and C++ class for WINSDK Platform so easy to
 *          implement a overide or wrapping inherited classes.
 * http://krkim.net,http://durumul.com , http://durumul.blogspot.com 
 *
 * Copyright(c) 2001,2006,2009 KRKIM (DURUMUL.COM) Allrights reserved.
 * mailto:durumul@gmail.com,mailto:krkim@durumul.com
 *
 * This material is provided "as is", with absolutely no warranty expressed
 * or implied. Any use is at your own risk.
 *
 * Permission to use or copy this software for any purpose is hereby granted
 * without fee, provided the above notices are retained on all copies.
 * Permission to modify the code and to distribute modified code is granted,
 * provided the above notices are retained, and a notice that the code was
 * modified is included with the above copyright notice.
 * official release : http://www.durumul.com/kxlib or http://krkim.net
 *
 */
/*
           ===================================================
           ////////////////// KR's SKINBITMAP ////////////////
           ===================================================
		   DOK-DO AND EAST-SEA HAS BEEN KOREAN'S SINCE A.D 512!
     KOREAN ORIGINS FROM THE PAMIRS AND BAIKAL LAKES SINCE B.C 6000.

	Here are simple processing bitmap dib for an implements of skin.

	This software is provided "as is" with no expressed or implied warranty.
	The author accepts no liability for any damage/loss of business that
	this product may cause.
	
	For more get resource and dev info, visit at:
	http://www.krkim.net

	Thank you regards,
	Author: KyungRae Kim(KRKIM) 
	Location:The Greatest JUSIN Country, Korea. (대한민국,大韓民國)
*/

/* History
   -------
	Version 1.21 - 2008.09.17
		-Load 32bpp Bitmap with converting to 24bpp Bitmap.
	 
	Version 1.01 - 2007.09.21
		-Bugfix broken drawing image with GetClipRect() in Draw(),so remove it.
	Version 1.00 - 2007.09.17
		-These Load(),Load2(),Load3() functions return HBITMAP,
	different with class member m_hBitmap.
	The m_hBitmap is clone handle on everytime.
*/

/*
How to Use:
	1) Load(),Load2(),Load3() or LoadBitmap() to load image.
		these return HBITMAP, but it different with member m_hBitmap because it was cloned.
	2) To Draw, call Draw() function with SetDrawType() enable or direct call sub functions as
		DrawNormal(),DrawStretched(),DrawTiled() without DrawType setting. 
	3) To Draw external HBITMAP,first call ructor KFCBitmap(HBITMAP hBitmap).
		it will make new cloned HBITMAP with BITMAPINFO,DIBBits(PixelColorBits = RawImageData). 
	4) To Crop or Cut Image,call ClipBitmap().
		it is independent function.
	5) To make Region for Transparent,call BitmapToRegion().

	At least more help or how to,see member function "example(HDC hDC,LPSTR szImgFile)".
*/
//KFCBitmap is migrated from my other project source(SkinBitmap class).
#pragma once

#include "KFC.h"

_KFC_BEGIN_PACK(DC)

#define BFT_ICON   0x4349   /* 'IC' */
#define BFT_BITMAP 0x4d42   /* 'BM' */
#define BFT_CURSOR 0x5450   /* 'PT' */

#define PADWIDTH(x)	            (((x)*8 + 31)  & (~31))/8
#define WIDTHBYTES(i)           ((unsigned)((i+31)&(~31))/8)  /* ULONG aligned ! */
#define DibWidthBytesN(lpbi, n) (UINT)WIDTHBYTES((UINT)(lpbi)->biWidth * (UINT)(n))
#define DibWidthBytes(lpbi)     DibWidthBytesN(lpbi, (lpbi)->biBitCount)
struct IMGINFO{
	DWORD	dwEffWidth;			//< DWORD aligned scan line width
	BYTE*	pImage;				//< THE IMAGE BITS
};

class  KFCBitmap  
{
public:
	enum DRAWTYPE_PARAMS{	DRAW_NORMAL	=0,DRAW_TILE,DRAW_STRETCH};

	KFCBitmap();
	KFCBitmap(HBITMAP hBitmap);//attach extern HBITMAP into this.
	KFCBitmap(LPCTSTR szFilename,int nType = DRAW_NORMAL);
	KFCBitmap(HINSTANCE hInst,UINT nIDResource,int nType = DRAW_NORMAL);
	KFCBitmap(HDC hDC, int dx,int dy);//make empty BITMAP Image set to m_hBitmap on hDC Canvas.
	virtual ~KFCBitmap();
	void Attach(HBITMAP hBitmap);
	void Detach();

protected:
	BOOL CopyFrom(HBITMAP hBitmap);//Get BITMAPINFO and DIBBits(Pixel Color Bits,Raw ImageData) Info from given HBITMAP.

public:		// attributes
	virtual BOOL Inside(int x, int y);
	BITMAPINFO *	GetHeaderPtr() ;
	BYTE *			GetPixelPtr() ;
	RGBQUAD *		GetColorTablePtr() ;
	int				GetWidth() ;
	int				GetHeight() ;
	SIZE			GetBitmapSize();
	HPALETTE GetPalette()  { return m_hPal; }
	int GetDrawType() {return m_nDrawType;}
	void SetDrawType(int nType) {m_nDrawType = nType;}//nType is one of DRAW_NORMAL,DRAW_TILE,DRAW_STRETCH

	operator HBITMAP() { return m_hBitmap; }
	void operator = (KFCBitmap & bmp){
		if (bmp.m_hBitmap != m_hBitmap){
			Free ();
			/*HBITMAP hBitmap = */bmp.Release ();
			CopyFrom(m_hBitmap);
		}
	}

	HBITMAP Release (){
		HBITMAP h = m_hBitmap;
		m_hBitmap = 0;
		return h;
	}

public:		// operations
	BOOL		CreatePalette();
	void		ClearPalette();

	HPALETTE CreatePalette(KFCBitmap* pBmp);
	void CreateCompatible (HDC hDC, int width, int height);//make empty BITMAP Image set to m_hBitmap.
	DWORD GetPaletteSize();
	long GetSize();
	HBITMAP	LoadBitmap(HINSTANCE hInst,UINT ID);//load BMP,CUR,ICO from Resource ID and set to m_hBitmap.
	HBITMAP	LoadBitmap(HINSTANCE hInst,LPCTSTR ID); //load BMP,CUR,ICO from Resource STRING and set to m_hBitmap.
	HBITMAP Load(LPCTSTR szFilename);   
	HBITMAP	Load2(LPCTSTR szFilename);  //load BMP ,CUR,ICO basically and set to m_hBitmap.
	HBITMAP	Load3(LPCTSTR szFilename);  //load BMP ,GIF,JPG by other methods using OleLoadPicture and set to m_hBitmap.
	BOOL	Save(LPCTSTR szFilename);
	void	Free();

	BOOL Draw(HDC hDC, RECT& rectDC, RECT& rectDIB,LPRECT lpClipRect = NULL);
	BOOL Draw(HDC hDC,LPRECT lprectDC = NULL , LPRECT lprectDIB = NULL,LPRECT lpClipRect = NULL);
	void DrawNormal(HDC hDC,RECT& rectDC,RECT& rectDIB);
	void DrawStretched (HDC hDC, RECT& rectDC, RECT& rectDIB);
	void DrawTiled (HDC hDC,RECT& rectDC,RECT& rectDIB);
	BOOL DrawTransparent(HDC hDC,COLORREF clrTrans, RECT& rcDest, RECT& rcSrc);
	HBITMAP ClipBitmap(HBITMAP hBitmap, int xSrc, int ySrc,int nWidth, int nHeight);//crop hBitmap image and return
	void DrawBitmap(HDC hDC, KFCBitmap &bMap);
	HRGN BitmapToRegion(HBITMAP hBitmap, COLORREF cTransparentColor,COLORREF cTolerance = RGB(0,0,0));//make region by given color.
	BOOL RegionToFile(HRGN hRgn,LPSTR szFilename);//save HRGN into file.
	HRGN FileToRegion(LPSTR szFilename);//load RGNDATA file into HRGN.
	int			GetPalEntries() ;
	int			GetPalEntries( BITMAPINFOHEADER& infoHeader ) ;
	DWORD		GetBitsPerPixel() ;
	DWORD		LastByte( DWORD BitsPerPixel, DWORD PixelCount ) ;
	DWORD		GetBytesPerLine( DWORD BitsPerPixel, DWORD Width ) ;
	BOOL		PadBits();
	BOOL		UnPadBits();
	int		GetColorCount() ;
	void example(HDC hDC,LPCTSTR szImgFile);
	BOOL IsValid() { return (m_hBitmap != NULL);}
	int GetEffectWidth();
	virtual int  GetIndex(int x, int y);
	BOOL GetPalRGB( int index, unsigned char *red, unsigned char *green, unsigned char *blue);
	int GetPalIndex( unsigned char red,unsigned char green,unsigned char blue);
	BOOL GetRGB(int x, int y, byte* r, byte* g, byte* b,byte *a = 0);
	BOOL SetIndex(int x, int y, int index);
	BOOL SetRGB(int x, int y, byte r, byte g, byte b);
	void Bitfield2RGB(BYTE *src, DWORD redmask, DWORD greenmask, DWORD bluemask, BYTE bpp);
	void Bitfield2RGB2(BYTE *src, DWORD redmask, DWORD greenmask, DWORD bluemask, BYTE bpp);
	HBITMAP GetHandle() { return m_hBitmap;}
private:
	int m_nDrawType;	

	HPALETTE		m_hPal;
	BOOL			m_bIsPadded;
	HBITMAP			m_hBitmap;

public:
	BITMAPINFOHEADER    head; //standard header
	BITMAPINFO *	m_pBI;
	BYTE       *	m_pPixelBits;
	BOOL			m_bConvert32To24bpp;
	long			m_effWidth; /*2008.08.26 KRKIM,Added Effective scan line width*/

};

_KFC_END_PACK
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
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
/* 
 * $Id: KFCBitmap.cpp 3 2009-12-20 19:12:53Z krkim $ $Revision: 3 $
 * $HeadURL: https://krkim-laptop/svn/KFC/trunk/KFCBitmap.cpp $
 * official release : http://www.durumul.com/kxlib or http://krkim.net
 */

//#include "stdafx.h"
//#include <olectl.h>
//#include <tchar.h>
//#include <//assert.h>
#include <windows.h>
//#include <wingdi.h>
//#include <math.h>
#include "KFCBitmap.h"

#pragma comment(lib,"Msimg32.lib")
_KFC_BEGIN_PACK(DC)
//This source codes are compatible with SDK(non MFC).
//krkim (c)

#define DibSizeImage(lpbi)      ((lpbi)->biSizeImage == 0 \
	? ((DWORD)(UINT)DibWidthBytes(lpbi) * (DWORD)(UINT)(lpbi)->biHeight) \
	: (lpbi)->biSizeImage)

#define DibNumColors(lpbi)      ((lpbi)->biClrUsed == 0 && (lpbi)->biBitCount <= 8 \
	? (int)(1 << (int)(lpbi)->biBitCount)          \
	: (int)(lpbi)->biClrUsed)

#define FixBitmapInfo(lpbi)     if ((lpbi)->biSizeImage == 0)                 \
	(lpbi)->biSizeImage = DibSizeImage(lpbi); \
	if ((lpbi)->biClrUsed == 0)                   \
	(lpbi)->biClrUsed = DibNumColors(lpbi);   \

_KFC_END_PACK

HPALETTE KFCBitmap::CreatePalette(KFCBitmap* pBmp)
{
	HPALETTE hPal;
	//assert( pBmp );
	int cPaletteEntries = pBmp->GetPalEntries();
	int cPalette = sizeof(LOGPALETTE) +
		sizeof(PALETTEENTRY) * cPaletteEntries;
	// Since the LOGPALETTE structure is open-ended, you
	// must dynamically allocate it, rather than using one
	// off the stack.
	LOGPALETTE* pPal = (LOGPALETTE*)new BYTE[cPalette];
	RGBQUAD*    pColorTab = pBmp->GetColorTablePtr();
	pPal->palVersion = 0x300;// Windows 3.0 version
	pPal->palNumEntries = (WORD)cPaletteEntries;
	// Roll through the color table, and add each color to
	// the logical palette.
	for( int ndx = 0; ndx < cPaletteEntries; ndx++ )
	{
		pPal->palPalEntry[ndx].peRed   = pColorTab[ndx].rgbRed;
		pPal->palPalEntry[ndx].peGreen = pColorTab[ndx].rgbGreen;
		pPal->palPalEntry[ndx].peBlue  = pColorTab[ndx].rgbBlue;
		pPal->palPalEntry[ndx].peFlags = NULL;
	}
	hPal = ::CreatePalette( pPal );
	delete [] (BYTE*)pPal;
	pPal = 0;
	return hPal;
}

KFCBitmap::KFCBitmap()
{
	m_pPixelBits = NULL;
	m_pBI = NULL;
	m_hPal = NULL;
	m_bIsPadded = FALSE;
	m_nDrawType = DRAW_NORMAL;
	m_hBitmap = NULL;
	m_effWidth = 0;
	m_bConvert32To24bpp = FALSE;
}

KFCBitmap::KFCBitmap(HBITMAP hBitmap)
{
	m_pPixelBits = NULL;
	m_pBI = NULL;
	m_hPal = NULL;
	m_bIsPadded = FALSE;
	m_nDrawType = DRAW_NORMAL;
	m_hBitmap = NULL;
	m_bConvert32To24bpp = FALSE;
	CopyFrom(hBitmap);
}

KFCBitmap::KFCBitmap(LPCTSTR szFilename,int nType)
{
	m_pPixelBits = NULL;
	m_pBI = NULL;
	m_hPal = NULL;
	m_bIsPadded = FALSE;
	m_nDrawType = nType;
	m_hBitmap = NULL;
	m_bConvert32To24bpp = FALSE;
	Load(szFilename);
}

KFCBitmap::KFCBitmap(HINSTANCE hInst,UINT nIDResource,int nType)
{
	m_pPixelBits = NULL;
	m_pBI = NULL;
	m_hPal = NULL;
	m_bIsPadded = FALSE;
	m_nDrawType = nType;
	m_hBitmap = NULL;
	m_bConvert32To24bpp = FALSE;
	LoadBitmap(hInst,nIDResource);
}

KFCBitmap::KFCBitmap(HDC hDC, int dx, int dy)//make empty BITMAP Image set to m_hBitmap on hDC Canvas.
{
	CreateCompatible(hDC, dx, dy);
}

void KFCBitmap::CreateCompatible (HDC hDC, int width, int height)//make empty BITMAP Image set to m_hBitmap.
{
	Free ();
	m_hBitmap = ::CreateCompatibleBitmap (hDC, width, height);
}

KFCBitmap::~KFCBitmap() 
{
	Free();
}

//이클래스를 지역 변수로 선언하여 임시로 사용할 경우,클래스가 소멸되어
//Free() 가 실행되어 m_hBitmap = NULL 이 된다.
//따라서 Load() 계열 함수로 인해 리턴된 HBITMAP 를 외부변수로 가지고 있다가
//생성자 KFCBitmap(HBITMAP hBitmap) 을 호출하여 다시 클래스화 할수 있다.

void KFCBitmap::Free() 
{
	if (m_hBitmap)
		::DeleteObject (m_hBitmap);
	m_hBitmap = NULL;

	if(m_pBI)
		delete [] (BYTE*)m_pBI;
	if(m_pPixelBits)
		delete [] m_pPixelBits;
	if(m_hPal)
		//delete m_hPal; //bugfix 2011.05.05
		DeleteObject(m_hPal);
	m_pBI = 0;
	m_pPixelBits = 0;
	m_hPal = 0;
}

void KFCBitmap::Attach(HBITMAP hBitmap)
{
	Free();
	CopyFrom(hBitmap); 
}

void KFCBitmap::Detach()
{
	Free();
}

BOOL KFCBitmap::CopyFrom(HBITMAP hBitmap) 
{
	BITMAP bmHdr;
	if(!hBitmap) return FALSE;
	//try {
		// Get the pSrcBitmap info
		//pSrcBitmap->GetObject(sizeof(BITMAP), &bmHdr);
		::GetObject(hBitmap, sizeof(bmHdr), &bmHdr);

		if(m_hBitmap == NULL){
			m_hBitmap = CreateBitmapIndirect(&bmHdr);
			//DWORD dwError = GetLastError();

			//assert( m_hBitmap );
			//if(!m_hBitmap)
			//	throw TEXT("could not create copy");
		}
		// Reallocate space for the image data
		if( m_pPixelBits ){
			delete [] m_pPixelBits;
			m_pPixelBits = 0;
		}

		DWORD dwWidth;
		if (bmHdr.bmBitsPixel > 8)
			dwWidth = PADWIDTH(bmHdr.bmWidth * 3);
		else
			dwWidth = PADWIDTH(bmHdr.bmWidth);

		m_pPixelBits = new BYTE[dwWidth*bmHdr.bmHeight];
		//if( !m_pPixelBits )
		//	throw TEXT("could not allocate data storage\n" );
		
		m_effWidth = (long)(((long)bmHdr.bmWidth*bmHdr.bmBitsPixel + 31) / 32) * 4;//2008.08.26 krkim

		// Set the appropriate number of colors base on BITMAP structure info
		WORD wColors;
		switch( bmHdr.bmBitsPixel ) {//depth
			case 1 : wColors = 2;
				break;
			case 4 : wColors = 16;
				break;
			case 8 : wColors = 256;
				break;
			default: wColors = 0;
				break;
		}

		// Re-allocate and populate BITMAPINFO structure
		if( m_pBI ) {
			delete [] (BYTE*)m_pBI;
			m_pBI = 0;
		}

		m_pBI = (BITMAPINFO*)new BYTE[sizeof(BITMAPINFOHEADER) + wColors*sizeof(RGBQUAD)];
		//if( !m_pBI )
		//	throw TEXT("could not allocate BITMAPINFO struct\n");

		// Populate BITMAPINFO header info
		m_pBI->bmiHeader.biSize = sizeof(BITMAPINFOHEADER);
		m_pBI->bmiHeader.biWidth = bmHdr.bmWidth;
		m_pBI->bmiHeader.biHeight = bmHdr.bmHeight;
		m_pBI->bmiHeader.biPlanes = bmHdr.bmPlanes;

		if( bmHdr.bmBitsPixel > 8 )
			m_pBI->bmiHeader.biBitCount = 24;
		else
			m_pBI->bmiHeader.biBitCount = bmHdr.bmBitsPixel;

		m_pBI->bmiHeader.biCompression = BI_RGB;
		m_pBI->bmiHeader.biSizeImage = ((((bmHdr.bmWidth * bmHdr.bmBitsPixel) + 31) & ~31) >> 3) * bmHdr.bmHeight;
		m_pBI->bmiHeader.biXPelsPerMeter = 0;
		m_pBI->bmiHeader.biYPelsPerMeter = 0;
		m_pBI->bmiHeader.biClrUsed = 0;
		m_pBI->bmiHeader.biClrImportant = 0;
		HDC dc = ::GetDC(NULL);
		// Now actually get the bits
		int test;
		test = ::GetDIBits(dc, (HBITMAP)hBitmap,
			0, (WORD)bmHdr.bmHeight, m_pPixelBits, m_pBI, DIB_RGB_COLORS);

		m_effWidth = (long)(((long)bmHdr.bmWidth*bmHdr.bmBitsPixel + 31) / 32) * 4;//2008.08.26 krkim

		::ReleaseDC(NULL, dc);
		// check that we scanned in the correct number of bitmap lines
		//if( test != (int)bmHdr.bmHeight )
		//	throw TEXT("call to GetDIBits did not return full number of requested scan lines\n");

		CreatePalette();
		m_bIsPadded = FALSE;
	//} catch( TCHAR * /*psz*/) {
	//if( m_pPixelBits ){
	//	delete [] m_pPixelBits;
	//	m_pPixelBits = 0;
	//}
	//if( m_pBI ){
	//	delete [] (BYTE*) m_pBI;
	//	m_pBI = 0;
	//}
	//return FALSE;
	//}
	return TRUE;
}

HBITMAP KFCBitmap::LoadBitmap(HINSTANCE hInst,UINT ID)
{ 
	BOOL bRet;
	Free();

	HBITMAP hBitmap = (HBITMAP)::LoadImage(hInst,MAKEINTRESOURCE(ID), IMAGE_BITMAP,0,0, LR_CREATEDIBSECTION);
	bRet = CopyFrom(hBitmap);
	return hBitmap;
}

HBITMAP KFCBitmap::LoadBitmap(HINSTANCE hInst,LPCTSTR pszID) 
{
	BOOL bRet;
	Free();
	HBITMAP hBitmap = (HBITMAP)::LoadImage(hInst,pszID, IMAGE_BITMAP,0,0, LR_CREATEDIBSECTION);
	bRet = CopyFrom(hBitmap);
	return hBitmap;
}

////////////////////////////////////////////////////////////////////////////////
/**
* turns a 16 or 32 bit bitfield image into a RGB image(24bpp)
*/
void KFCBitmap::Bitfield2RGB(BYTE *src, DWORD redmask, DWORD greenmask, DWORD bluemask, BYTE bpp)
{
	switch (bpp){
	case 16:
		{
			DWORD ns[3]={0,0,0};
			// compute the number of shift for each mask
			for (int i=0;i<16;i++){
				if ((redmask>>i)&0x01) ns[0]++;
				if ((greenmask>>i)&0x01) ns[1]++;
				if ((bluemask>>i)&0x01) ns[2]++;
			}
			ns[1]+=ns[0]; ns[2]+=ns[1];	ns[0]=8-ns[0]; ns[1]-=8; ns[2]-=8;
			// dword aligned width for 16 bit image
			long effwidth2=(((m_pBI->bmiHeader.biWidth + 1) / 2) * 4);
			WORD w;
			long y2,y3,x2,x3;
			BYTE *p=m_pPixelBits;
			// scan the buffer in reverse direction to avoid reallocations
			for (long y=m_pBI->bmiHeader.biHeight-1; y>=0; y--){
				y2=effwidth2*y;
				y3=m_effWidth*y;
				for (long x=m_pBI->bmiHeader.biWidth-1; x>=0; x--){
					x2 = 2*x+y2;
					x3 = 3*x+y3;
					w = (WORD)(src[x2]+256*src[1+x2]);
					p[  x3]=(BYTE)((w & bluemask)<<ns[0]);
					p[1+x3]=(BYTE)((w & greenmask)>>ns[1]);
					p[2+x3]=(BYTE)((w & redmask)>>ns[2]);
				}
			}
			break;
		}
	case 32:
		{
			DWORD ns[3]={0,0,0};
			// compute the number of shift for each mask
			for (int i=8;i<32;i+=8){
				if (redmask>>i) ns[0]++;
				if (greenmask>>i) ns[1]++;
				if (bluemask>>i) ns[2]++;
			}
			// dword aligned width for 32 bit image
			long effwidth4 = m_pBI->bmiHeader.biWidth * 4;
			long y4,y3,x4,x3;
			BYTE *p=m_pPixelBits;
			// scan the buffer in reverse direction to avoid reallocations
			for (long y=m_pBI->bmiHeader.biHeight-1; y>=0; y--){
				y4=effwidth4*y;
				y3=m_effWidth*y;
				for (long x=m_pBI->bmiHeader.biWidth-1; x>=0; x--){
					x4 = 4*x+y4;
					x3 = 3*x+y3;
					p[  x3]=src[ns[2]+x4];
					p[1+x3]=src[ns[1]+x4];
					p[2+x3]=src[ns[0]+x4];
				}
			}
		}

	}
	return;
}

void KFCBitmap::Bitfield2RGB2(BYTE *src, DWORD redmask, DWORD greenmask, DWORD bluemask, BYTE bpp)
{
	switch (bpp){
	case 16:
		{
			DWORD ns[3]={0,0,0};
			// compute the number of shift for each mask
			for (int i=0;i<16;i++){
				if ((redmask>>i)&0x01) ns[0]++;
				if ((greenmask>>i)&0x01) ns[1]++;
				if ((bluemask>>i)&0x01) ns[2]++;
			}
			ns[1]+=ns[0]; ns[2]+=ns[1];	ns[0]=8-ns[0]; ns[1]-=8; ns[2]-=8;
			// dword aligned width for 16 bit image
			long effwidth2=(((m_pBI->bmiHeader.biWidth + 1) / 2) * 4);
			WORD w;
			long y2,y3,x2,x3;
			BYTE *p=m_pPixelBits;
			// scan the buffer in reverse direction to avoid reallocations
			for (long y=m_pBI->bmiHeader.biHeight-1; y>=0; y--){
				y2=effwidth2*y;
				y3=m_effWidth*y;
				for (long x=m_pBI->bmiHeader.biWidth-1; x>=0; x--){
					x2 = 2*x+y2;
					x3 = 3*x+y3;
					w = (WORD)(src[x2]+256*src[1+x2]);
					p[  x3]=(BYTE)((w & bluemask)<<ns[0]);
					p[1+x3]=(BYTE)((w & greenmask)>>ns[1]);
					p[2+x3]=(BYTE)((w & redmask)>>ns[2]);
				}
			}
			break;
		}
	case 32:
		{
			DWORD ns[3]={0,0,0};
			// compute the number of shift for each mask
			for (int i=8;i<32;i+=8){
				if (redmask>>i) ns[0]++;
				if (greenmask>>i) ns[1]++;
				if (bluemask>>i) ns[2]++;
			}
			// dword aligned width for 32 bit image
			long effwidth4 = m_pBI->bmiHeader.biWidth * 4;
			long y4,y3,x4,x3;
			BYTE *p=m_pPixelBits;
			int c = 0;
			// scan the buffer in reverse direction to avoid reallocations
			for (long y=m_pBI->bmiHeader.biHeight-1; y>=0; y--){
				y4=effwidth4*y;
				y3=m_effWidth*y;
				for (long x=m_pBI->bmiHeader.biWidth-1; x>=0; x--){
					x4 = 4*x+y4;
					x3 = 4*x+y3;
					
					p[x3]  =src[ns[2]+x4];//r
					p[x3+1]=src[ns[1]+x4];//g
					p[x3+2]=src[ns[0]+x4];//b
					p[x3+3]=src[x4];//a
					if(p[x3+3] != 0){
						/*TRACE("src[ns[2]+x4] = %X\n",src[ns[2]+x4]);*/
						if(c == 0){
							MessageBox(NULL,"Detect Valid ARGB Pixel","Found Pixel",MB_OK);
							c = 1;
						}
					}
#if 1
					p[3+x3] = 255;
					if(p[x3] == 0 ) p[3+x3] = 0;
					else if(p[x3] <= 96 && p[1 + x3] <= 96 && p[2+x3] <= 96 )
						p[3+x3] = 50;

#if 0
					if(p[3+x3] == 0 ) p[3+x3] = 0;
					
					if(p[x3] >= 196 || p[1 + x3] >= 196 || p[2+x3] >= 196 )
					{
						p[3+x3] = 255;
					}
					else if(p[x3] >= 128 || p[1 + x3] >= 128 || p[2+x3] >= 128 )
					{
						p[3+x3] = 255;	
					}
					else if(p[x3] >= 96 || p[1 + x3] >= 96 || p[2+x3] >= 96 )
					{
						p[3+x3] = 255;	
					}
					//else if(p[x3] >= 16 || p[1 + x3] >= 16 || p[2+x3] >= 16 )
					//	p[3+x3] = 16;
					else if(p[x3] <= 5 || p[1 + x3] <= 5 || p[2+x3] <= 5 ){
						p[3+x3] = 1;
					}
					else
						p[3+x3] = 255;
#endif
#endif
				}

			}
		}

	}
	return;
}

//load BMP,CUR,ICO and set to m_hBitmap by open file directly,best performance,
//more fast than Load() and Load3(). recommend use it!(권장함수) 
//이 Load() 계열 함수가 리턴하는 HBITMAP는 내부의 m_hBitmap과는 다르다.

HBITMAP KFCBitmap::Load(LPCTSTR szFilename) 
{
	HBITMAP hBitmap = NULL;
	m_bConvert32To24bpp = 0;
	Free();
#if 1
	hBitmap = (HBITMAP)::LoadImage(NULL,(LPCTSTR)szFilename,IMAGE_BITMAP,0,0,LR_LOADFROMFILE);
	if(!hBitmap){
		//DWORD dwErr = GetLastError();
		return NULL;

	}
	//m_hBitmap = hBitmap;
	if(m_hBitmap == NULL){
		BITMAP bmHdr;
		::GetObject(hBitmap, sizeof(bmHdr), &bmHdr);
		m_hBitmap = CreateBitmapIndirect(&bmHdr);
		//if(!m_hBitmap)
		//	throw TEXT("could not create copy");
	}
#endif
	BOOL fReturn = TRUE;
	HANDLE hFile = INVALID_HANDLE_VALUE;
	//try {
		delete [] (BYTE*)m_pBI;
		delete [] m_pPixelBits;
		m_pBI = 0;
		m_pPixelBits = 0;
		ULONGLONG       dwStart = 0;
		// open file
		hFile = CreateFile((LPCTSTR)szFilename, GENERIC_READ,FILE_SHARE_READ, NULL, OPEN_EXISTING, 0, NULL);
		if(INVALID_HANDLE_VALUE == hFile)
			fReturn  = FALSE;
		else{
			//get file pointer
			LARGE_INTEGER liPos;
			liPos.QuadPart = 0;
			liPos.LowPart = ::SetFilePointer(hFile, liPos.LowPart, &liPos.HighPart ,FILE_CURRENT);
			dwStart = liPos.QuadPart;
			BOOL bRead;
			DWORD dwBytesRead = 0;
			
			//
			// Check to make sure we have a bitmap. The first two bytes must
			// be 'B' and 'M'.
			BITMAPFILEHEADER fileHeader;
			bRead = ReadFile(hFile,&fileHeader, sizeof(fileHeader), &dwBytesRead, NULL);

			//if( fileHeader.bfType != BFT_BITMAP )
			//	throw TEXT("Error:Unexpected file type, not a DIB\n");

			BITMAPINFOHEADER infoHeader;
			bRead = ReadFile(hFile,&infoHeader, sizeof(infoHeader), &dwBytesRead, NULL);
			//if( infoHeader.biSize != sizeof(infoHeader) )
			//	throw TEXT("Error:OS2 PM BMP Format not supported\n");

			// Store the sizes of the DIB structures
			int cPaletteEntries;
			cPaletteEntries = GetPalEntries( infoHeader );
			int cColorTable = 256 * sizeof(RGBQUAD);
			int cInfo = sizeof(BITMAPINFOHEADER) + cColorTable;
			int cPixels = fileHeader.bfSize - fileHeader.bfOffBits;

			DWORD dwCompression=infoHeader.biCompression;
			DWORD dwBitCount=infoHeader.biBitCount; //preserve for BI_BITFIELDS compression <Thomas Ernst>

			//
			// Allocate space for a new bitmap info header, and copy
			// the info header that was loaded from the file. Read the
			// the file and store the results in the color table.
			//32bpp 이미지를 24bpp이미지로 컨버팅하기위한 전주곡
			//24bpp 는(8bpp 이상) 팔레트가없고 RGB가 BGR순으로 기록되어있다.(3바이트)
			//32bpp 는 BITFIELD 압축방식이라면 ARGB가 기록되어있다.(4바이트)
			//따라서 32bpp의 이미지데이타를 24bpp로 변환하기로 한다.
			//단순출력의 경우 변환필요없음 -krkim-

			DWORD wBpp = infoHeader.biBitCount;
			if(m_bConvert32To24bpp){
				if		(wBpp <= 1)	wBpp = 1;
				else if (wBpp <= 4)	wBpp = 4;
				else if (wBpp <= 8)	wBpp = 8;
				else				wBpp = 24;

				// set the correct bpp value
				switch (wBpp){
					case 1:
						infoHeader.biClrUsed = 2;	break;
					case 4:
						infoHeader.biClrUsed = 16; break;
					case 8:
						infoHeader.biClrUsed = 256; break;
					default:
						infoHeader.biClrUsed = 0;
				}
				infoHeader.biBitCount = (WORD)wBpp;
			}
			m_effWidth = (long)(((long)infoHeader.biWidth*wBpp + 31) / 32) * 4;//2008.08.26 krkim
			if(m_bConvert32To24bpp){
				infoHeader.biSizeImage = m_effWidth * infoHeader.biHeight;
				infoHeader.biCompression = BI_RGB;
				infoHeader.biPlanes = 1;			// must be 1
			}
			m_pBI = (BITMAPINFO*)new BYTE[cInfo];

			memcpy( m_pBI, &infoHeader, sizeof(BITMAPINFOHEADER) );
			int cors;
			cors = DibNumColors(&m_pBI->bmiHeader);
			memset(m_pBI->bmiColors,0,sizeof(RGBQUAD) * 1);

			//BITMAPINFOHEADER 이후에는 256컬러는 COLORTABLE이 256개 오고 16BPP이상은 없다.
			//단 32BITS의 BIT_FIELDS는 3개가 온다.
#if 0
			m_pBI->bmiColors[0].rgbBlue = 0x00;
			m_pBI->bmiColors[0].rgbGreen = 0x00;
			m_pBI->bmiColors[0].rgbRed = 0x00;
			m_pBI->bmiColors[0].rgbReserved= 0xff;
			m_pBI->bmiColors[1].rgbBlue = 0x00;
			m_pBI->bmiColors[1].rgbGreen = 0x00;
			m_pBI->bmiColors[1].rgbRed = 0xFF;
			m_pBI->bmiColors[1].rgbReserved= 0x00;
			m_pBI->bmiColors[2].rgbBlue = 0x00;
			m_pBI->bmiColors[2].rgbGreen = 0xFF;
			m_pBI->bmiColors[2].rgbRed = 0x00;
			m_pBI->bmiColors[2].rgbReserved= 0x00;
#endif
			if(infoHeader.biClrUsed)//it exists palette info
				bRead = ReadFile(hFile,((BYTE*)m_pBI) + sizeof(BITMAPINFOHEADER),cColorTable, &dwBytesRead, NULL);

			switch (dwBitCount) {
				case 32://convert to 24bit
					DWORD bfmask[3];
					if (dwCompression == BI_BITFIELDS)//color masks 
					{
						bRead = ReadFile(hFile,bfmask,12, &dwBytesRead, NULL);
						memcpy(m_pBI->bmiColors,bfmask,12);
					} else {
						bfmask[0]=0x00FF0000;//R 
						bfmask[1]=0x0000FF00;//G
						bfmask[2]=0x000000FF;//B
					}
					if (dwCompression == BI_BITFIELDS || dwCompression == BI_RGB){
						LARGE_INTEGER liOff;
						liOff.QuadPart = dwStart + fileHeader.bfOffBits;
						liOff.LowPart = ::SetFilePointer(hFile, liOff.LowPart, &liOff.HighPart,FILE_BEGIN);
						long imagesize=4*infoHeader.biHeight*infoHeader.biWidth;
						if(m_bConvert32To24bpp){
							BYTE* buff32=(BYTE*)malloc(imagesize);
							if (buff32)
								bRead = ReadFile(hFile,buff32, imagesize, &dwBytesRead, NULL);
							
							m_pPixelBits = new BYTE[imagesize];
							Bitfield2RGB(buff32,bfmask[0],bfmask[1],bfmask[2],32);
							free(buff32);
						}
						else if(dwCompression == BI_BITFIELDS){//convert to RGBA mode
							BYTE* buff32=(BYTE*)malloc(imagesize);
							if (buff32)
								bRead = ReadFile(hFile,buff32, imagesize, &dwBytesRead, NULL);
							
							m_pPixelBits = new BYTE[imagesize];
							Bitfield2RGB2(buff32,bfmask[0],bfmask[1],bfmask[2],32);
							m_pBI->bmiHeader.biCompression = BI_RGB;
							m_pBI->bmiHeader.biBitCount = 32;
							free(buff32);
						}
						else{//32bpp RGBA Mode
							m_pPixelBits = new BYTE[cPixels];
							bRead = ReadFile(hFile,m_pPixelBits, cPixels, &dwBytesRead, NULL);
						}

					}
					break;
				default: // <=256
					//load colortable(palette)
					bRead = ReadFile(hFile,((BYTE*)m_pBI) + sizeof(BITMAPINFOHEADER),cColorTable, &dwBytesRead, NULL);

					//
					// Allocate space for the pixel area, and load the pixel
					// info from the file.
					m_pPixelBits = new BYTE[cPixels];

					LARGE_INTEGER liOff;
					liOff.QuadPart = dwStart + fileHeader.bfOffBits;
					liOff.LowPart = ::SetFilePointer(hFile, liOff.LowPart, &liOff.HighPart,FILE_BEGIN);
					//liOff.QuadPart is new pointer

					bRead = ReadFile(hFile,m_pPixelBits, cPixels, &dwBytesRead, NULL);
					break;
			}
			//FixBitmapInfo(&m_pBI->bmiHeader);
			CreatePalette();
			m_bIsPadded = TRUE;
		}
#ifdef _DEBUG
	//} catch( TCHAR * psz ) {
	//	psz;
	//	TRACELOG((LPSTR)psz );
#else
	//} catch( TCHAR * ) {
#endif
	//	fReturn = FALSE;
	//}
	if(hFile !=INVALID_HANDLE_VALUE)
		CloseHandle(hFile);

	if(fReturn)
		return hBitmap;
	return NULL;
}

//Load BMP(ico,cursor) only simple function
HBITMAP KFCBitmap::Load2(LPCTSTR szFilename)
{
	BOOL bRet;
	Free();
	HBITMAP hBitmap;
	hBitmap = (HBITMAP)::LoadImage(NULL,(LPCTSTR)szFilename,IMAGE_BITMAP,0,0,LR_LOADFROMFILE);
	bRet = CopyFrom(hBitmap);
	return hBitmap;
}

//Load *.bmp, *.jpg, *.gif, *.ico, *.emf, or *.wmf files
HBITMAP KFCBitmap::Load3(LPCTSTR szFilename)
{
	HBITMAP hBitmap = NULL;
	LPPICTURE gpPicture;

	// open file
	HANDLE hFile = CreateFile((LPCTSTR)szFilename, GENERIC_READ, 0, NULL, OPEN_EXISTING, 0, NULL);
	//assert(INVALID_HANDLE_VALUE != hFile);

	// get file size
	DWORD dwFileSize = GetFileSize(hFile, NULL);
	//assert(-1 != dwFileSize);

	LPVOID pvData = NULL;
	// alloc memory based on file size
	HGLOBAL hGlobal = GlobalAlloc(GMEM_MOVEABLE, dwFileSize);
	//assert(NULL != hGlobal);

	pvData = GlobalLock(hGlobal);
	//assert(NULL != pvData);

	DWORD dwBytesRead = 0;
	// read file and store in global memory
	BOOL bRead;
	bRead = ReadFile(hFile, pvData, dwFileSize, &dwBytesRead, NULL);
	//assert(FALSE != bRead);
	GlobalUnlock(hGlobal);
	CloseHandle(hFile);

	LPSTREAM pstm = NULL;
	// create IStream* from global memory
	HRESULT hr = CreateStreamOnHGlobal(hGlobal, TRUE, &pstm);
	//assert(SUCCEEDED(hr) && pstm);

	// Create IPicture from image file
	hr = ::OleLoadPicture(pstm, dwFileSize, FALSE, IID_IPicture, (LPVOID *)&gpPicture);
	//assert(SUCCEEDED(hr) && gpPicture);	
	pstm->Release();
	if(SUCCEEDED(hr) && gpPicture){
		OLE_HANDLE m_picHandle;
		gpPicture->get_Handle(&m_picHandle);
		HDC hdc = CreateCompatibleDC(NULL);
		SelectObject(hdc,(HGDIOBJ)(OLE_HANDLE)m_picHandle);
		hBitmap = (HBITMAP)GetCurrentObject(hdc, OBJ_BITMAP);
		DeleteDC(hdc);
	}
	Free();

	BOOL bRet;
	bRet = CopyFrom(hBitmap);
	return hBitmap;
}

BOOL KFCBitmap::Save(LPCTSTR szFilename) {
	//assert( m_pBI );
	//assert( m_pPixelBits );

	// open file
	HANDLE hFile = CreateFile(szFilename, GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, 0, NULL);
	if(INVALID_HANDLE_VALUE == hFile) return FALSE;

	BITMAPFILEHEADER bmfHdr;

	DWORD dwPadWidth = PADWIDTH(GetWidth());

	// Make sure bitmap data is in padded format
	PadBits();

	bmfHdr.bfType = BFT_BITMAP;
	// initialize to BitmapInfo size
	DWORD dwImageSize= m_pBI->bmiHeader.biSize;
	// Add in palette size
	WORD wColors = (WORD)GetColorCount();
	WORD wPaletteSize = (WORD)(wColors*sizeof(RGBQUAD));
	dwImageSize += wPaletteSize;

	// Add in size of actual bit array
	dwImageSize += PADWIDTH((GetWidth()) * DWORD(m_pBI->bmiHeader.biBitCount)/8) * GetHeight();
	m_pBI->bmiHeader.biSizeImage = 0;
	bmfHdr.bfSize = dwImageSize + sizeof(BITMAPFILEHEADER);
	bmfHdr.bfReserved1 = 0;
	bmfHdr.bfReserved2 = 0;
	bmfHdr.bfOffBits = (DWORD)sizeof(BITMAPFILEHEADER) + m_pBI->bmiHeader.biSize + wPaletteSize;
	DWORD nWritten;
	BOOL bWrite;
	bWrite = ::WriteFile(hFile,&bmfHdr, sizeof(BITMAPFILEHEADER), &nWritten, NULL);
	bWrite = ::WriteFile(hFile,m_pBI, sizeof(BITMAPINFO) + (wColors-1)*sizeof(RGBQUAD), &nWritten, NULL);
	bWrite = ::WriteFile(hFile,m_pPixelBits,DWORD((dwPadWidth*(DWORD)m_pBI->bmiHeader.biBitCount*GetHeight())/8), &nWritten, NULL);
	CloseHandle(hFile);
	return TRUE;
}      

BOOL KFCBitmap::CreatePalette() {
	if( m_hPal )
		DeleteObject(m_hPal);
	m_hPal = NULL;

	//assert( m_pBI );
	// We only need a palette, if there are <= 256 colors.
	// otherwise we would bomb the memory.
	if( m_pBI->bmiHeader.biBitCount <= 8 )
		m_hPal = CreatePalette(this);
	return m_hPal ? TRUE : FALSE;
}

void KFCBitmap::ClearPalette() {
	if( m_hPal )
		DeleteObject(m_hPal);
	m_hPal = NULL;
}

// draw parts of the dib into a given area of the DC
BOOL KFCBitmap::Draw(HDC hDC,LPRECT lprectDC,LPRECT lprectDIB,LPRECT lpClipRect)
{
	RECT rcDC,rcImg;
	if(lprectDC)  rcDC =  *lprectDC;
	else 		  SetRect(&rcDC,0,0,-1,-1);
	if(lprectDIB) rcImg =  *lprectDIB;
	else          SetRect(&rcImg,0,0,-1,-1);
	return Draw(hDC,rcDC,rcImg,lpClipRect);
}
//draw main function with m_nDrawType set by SetDrawType()
BOOL KFCBitmap::Draw(HDC hDC, RECT& rectDC, RECT& rectDIB ,LPRECT lpClipRect)
{
	RECT rcDC,rcDIB;

	if(!m_hBitmap || !m_pBI)
		return FALSE;

	rcDC = rectDC;
	rcDIB = rectDIB;

	RECT mainbox; // (experimental) 칠하고 싶은 영역만 칠함
	if (lpClipRect){
		GetClipBox(hDC,&mainbox);
		HRGN rgn = CreateRectRgnIndirect(lpClipRect);
		ExtSelectClipRgn(hDC,rgn,RGN_AND);
		DeleteObject(rgn);
	}

	switch(m_nDrawType)
	{
	case DRAW_NORMAL:
		DrawNormal(hDC,rcDC,rcDIB);
		return TRUE;
	case DRAW_STRETCH:
		DrawStretched(hDC,rcDC,rcDIB);
		return TRUE;
	case DRAW_TILE:
		DrawTiled(hDC,rcDC,rcDIB);
		return TRUE;
	}
	return FALSE;
}

void KFCBitmap::DrawNormal(HDC hDC,RECT& rectDC,RECT& rectDIB)
{
	HPALETTE hOldPal = 0;
	if(!m_hBitmap || !m_pBI)
		return;

	int dw = rectDC.right - rectDC.left;
	int dh = rectDC.bottom - rectDC.top;
	int sh = rectDIB.bottom - rectDIB.top;

	if(dw < 0) dw = GetWidth() - rectDIB.left;
	if(dh < 0) dh = GetHeight() - rectDIB.top;
	if(sh < 0) sh = (dh >= 0) ? dh : GetHeight() - rectDIB.top;

	if( m_hPal ){
		hOldPal = SelectPalette(hDC,(HPALETTE)m_hPal, FALSE );
		RealizePalette(hDC);
	}
	// Make sure to use the stretching mode best for color pictures
	SetStretchBltMode(hDC,COLORONCOLOR);

	// DestX,DestY,DestWidth,DestHeight,SrcX,SrcY(from left-bottom to up),
	// StartScan, NumScans,color data raw image ,BITMAPINFO header data,color usage
	int dibtop = GetHeight() - rectDIB.top - sh;

	SetDIBitsToDevice(hDC,rectDC.left,rectDC.top,dw,dh,rectDIB.left,dibtop,
		0,GetHeight(),GetPixelPtr(),GetHeaderPtr(),DIB_RGB_COLORS);

	if(hOldPal)
		SelectPalette(hDC, hOldPal, FALSE );
}

// DrawDib uses StretchDIBits to display the bitmap. -높이가 같아야한다.
void KFCBitmap::DrawStretched(HDC hDC,RECT& rectDC,RECT& rectDIB)
{
	HPALETTE hOldPal = 0;
	if(!m_hBitmap || !m_pBI)
		return;

	int dw = rectDC.right - rectDC.left;
	int dh = rectDC.bottom - rectDC.top;
	int sw = rectDIB.right - rectDIB.left;
	int sh = rectDIB.bottom - rectDIB.top;

	if (dw < 0) dw = GetWidth() - rectDIB.left;
	if (dh < 0) dh = GetHeight() - rectDIB.top;
	if (sw < 0) sw = GetWidth() - rectDIB.left;
	if (sh < 0) sh = GetHeight() - rectDIB.top;

	if(m_hPal){
		hOldPal = SelectPalette(hDC,(HPALETTE)m_hPal, FALSE );
		RealizePalette(hDC);
	}
	// Make sure to use the stretching mode best for color pictures
	SetStretchBltMode(hDC,COLORONCOLOR);

	StretchDIBits(hDC,rectDC.left,rectDC.top,dw,dh,rectDIB.left,rectDIB.top,sw,sh,
		GetPixelPtr(),GetHeaderPtr(),DIB_RGB_COLORS,SRCCOPY);

	if(hOldPal)
		SelectPalette(hDC, hOldPal, FALSE );
}

void KFCBitmap::DrawTiled(HDC hDC,RECT& rectDC,RECT& rectDIB)
{
	HPALETTE hOldPal = 0;
	if(!m_hBitmap || !m_pBI)
		return;

	int sw = rectDIB.right - rectDIB.left;
	int sh = rectDIB.bottom - rectDIB.top;
	if (sw < 0) sw = GetWidth() - rectDIB.left;
	if (sh < 0) sh = GetHeight() - rectDIB.top;

	if(m_hPal){
		hOldPal = SelectPalette(hDC,(HPALETTE)m_hPal, FALSE );
		RealizePalette(hDC);
	}
	// Make sure to use the stretching mode best for color pictures
	SetStretchBltMode(hDC,COLORONCOLOR);

	int x=rectDC.left,y=rectDC.top;
	while(y<rectDC.bottom){
		while(x<rectDC.right){
			RECT rcDC;
			int w,h;

			SetRect(&rcDC,x,y,__min(x+sw,rectDC.right),__min(y+sh,rectDC.bottom));
			w = rcDC.right - rcDC.left;
			h = rcDC.bottom - rcDC.top;
			SetDIBitsToDevice(hDC,rcDC.left,rcDC.top,w,h,rectDIB.left,GetHeight() - rectDIB.top - sh,
				0,						// StartScan
				GetHeight(),			// NumScans
				GetPixelPtr(),			// color data - rawimage
				GetHeaderPtr(),			// header data - BITMAPINFO
				DIB_RGB_COLORS			// color usage
				);
			x+=sw;
		}
		x=rectDC.left;
		y+=sh;
	}
	if(hOldPal)
		SelectPalette(hDC, hOldPal, FALSE );
}

BOOL KFCBitmap::DrawTransparent(HDC hDC,COLORREF crTransparentColor, RECT& rectDC, RECT& rectDIB)
{
	RECT rcDC,rcBmp;
	rcDC = rectDC;
	rcBmp = rectDIB;

	if(IsRectEmpty(&rcDC) || (rcDC.left == 0 && rcDC.top == 0 && rcDC.right == 0 && rcDC.right == 0)) 
		::GetClipBox(hDC,&rcDC);
	if(IsRectEmpty(&rcBmp) || (rcBmp.left == 0 && rcBmp.top == 0 && rcBmp.right == 0 && rcBmp.right == 0)) 
		SetRect(&rcBmp,0,0,GetWidth(),GetHeight());

	int dw = rcDC.right - rcDC.left;
	int dh = rcDC.bottom - rcDC.top;
	int sw = rcBmp.right - rcBmp.left;
	int sh = rcBmp.bottom - rcBmp.top;

	if (dw < 0) dw = GetWidth() - rcBmp.left;
	if (dh < 0) dh = GetHeight() - rcBmp.top;
	if (sw < 0) sw = GetWidth() - rcBmp.left;
	if (sh < 0) sh = GetHeight() - rcBmp.top;
	int w = GetWidth();
	int h = GetHeight();
	//CDC memDC;
	HDC hmemDC;
	HBITMAP hNewBitmap,hOldBitmap = NULL;

	hmemDC = ::CreateCompatibleDC(hDC);
	hNewBitmap = ::CreateCompatibleBitmap(hDC,w,h);
	hOldBitmap = (HBITMAP)SelectObject(hmemDC,hNewBitmap);
	RECT rcmemDC;
	SetRect(&rcmemDC,0,0,dw,dh);
	DrawNormal(hmemDC,rcmemDC,rcBmp);
	//BitBlt(hDC,rcDC.left,rcDC.top,dw,dh,hmemDC,0,0,SRCCOPY); //test coordinate
	BOOL flag;
	flag = ::TransparentBlt(hDC,rcDC.left,rcDC.top,dw,dh,
		hmemDC,0,0,dw,dh,crTransparentColor);
	if(hOldBitmap)
		SelectObject(hmemDC,hOldBitmap);

	//call neccessary ,if not memory leaks.
	::DeleteDC(hmemDC);
	::DeleteObject(hNewBitmap);
#if 0
	CEZMemDC memDC(pDC,&rcDC,TRUE,TRUE	),imageDC(pDC,&rcDC,FALSE);
	CEZMonoDC backDC(pDC,&rcDC),maskDC(pDC,&rcDC);
	DrawNormal(&imageDC,rcDC,rcBmp);
	COLORREF clrImageOld = imageDC.SetBkColor(clrTrans);
	maskDC.BitBlt(rcDC.left,rcDC.top,rcDC.Width(),rcDC.Height(),&imageDC,rcDC.left,rcDC.top,SRCCOPY);
	imageDC.SetBkColor(clrImageOld);


	backDC.BitBlt(rcDC.left,rcDC.top,rcDC.Width(),rcDC.Height(),&maskDC,rcDC.left,rcDC.top,NOTSRCCOPY);

	memDC.BitBlt(rcDC.left,rcDC.top,rcDC.Width(),rcDC.Height(),&maskDC,rcDC.left,rcDC.top,SRCAND);

	imageDC.BitBlt(rcDC.left,rcDC.top,rcDC.Width(),rcDC.Height(),&backDC,rcDC.left,rcDC.top,SRCAND);

	memDC.BitBlt(rcDC.left,rcDC.top,rcDC.Width(),rcDC.Height(),&imageDC,rcDC.left,rcDC.top,SRCPAINT);
#endif
	return TRUE;
}

void KFCBitmap::DrawBitmap(HDC hDC, KFCBitmap &bMap)
{
	BITMAP bm;

	::GetObject(bMap, sizeof(bm), &bm);

	HDC memdc = ::CreateCompatibleDC(NULL);
	HBITMAP h = (HBITMAP)::SelectObject(memdc, bMap);
	::BitBlt(hDC, 0, 0, bm.bmWidth, bm.bmHeight, memdc, 0, 0, SRCCOPY);
	::SelectObject(memdc, h);

	// watch out for those 
	// tricky memory leaks
	::DeleteDC(memdc);
	::DeleteObject(h);
}

BITMAPINFO * KFCBitmap::GetHeaderPtr()
{
	//assert( m_pBI );
	//assert( m_pPixelBits );
	return m_pBI;
}

SIZE KFCBitmap::GetBitmapSize()
{
	SIZE s;
	s.cx = GetWidth();
	s.cy = GetHeight();
	return s;
}	

RGBQUAD * KFCBitmap::GetColorTablePtr()
{
	//assert( m_pBI );
	//assert( m_pPixelBits );
	RGBQUAD* pColorTable = 0;
	if( m_pBI != 0 ) {
		int cOffset = sizeof(BITMAPINFOHEADER);
		pColorTable = (RGBQUAD*)(((BYTE*)(m_pBI)) + cOffset);
	}
	return pColorTable;
}

BYTE * KFCBitmap::GetPixelPtr()
{
	//assert( m_pBI );
	//assert( m_pPixelBits );
	return m_pPixelBits;
}

int KFCBitmap::GetWidth()
{
	//assert( m_pBI );
	return m_pBI->bmiHeader.biWidth;
}

int KFCBitmap::GetHeight()
{
	//assert( m_pBI );
	return m_pBI->bmiHeader.biHeight;
}

int KFCBitmap::GetColorCount()
{
	//assert( m_pBI );

	switch( m_pBI->bmiHeader.biBitCount )	
	{
	case 1:		return 2;
	case 4:		return 16;
	case 8:		return 256;
	//case 16:    return pow(2,16);
	//case 24:    return pow(2,24);
	//case 32:	return pow(2,32);
	default:	return 0;
	}
}

int KFCBitmap::GetPalEntries()
{
	//assert( m_pBI );
	return GetPalEntries( *(BITMAPINFOHEADER*)m_pBI );
}

int KFCBitmap::GetPalEntries( BITMAPINFOHEADER& infoHeader )//number of colors
{
	int nReturn;
	if( infoHeader.biClrUsed == 0 )
		nReturn = ( 1 << infoHeader.biBitCount );
	else
		nReturn = infoHeader.biClrUsed;
	return nReturn;
}

DWORD KFCBitmap::GetPaletteSize()
{
	return (m_pBI->bmiHeader.biClrUsed * sizeof(RGBQUAD));
}

DWORD KFCBitmap::GetBitsPerPixel()//same as Depth
{
	//assert( m_pBI );
	return m_pBI->bmiHeader.biBitCount;
}

/**
* \return the size in bytes of the internal pDib object
*/
long KFCBitmap::GetSize()
{
	return m_pBI->bmiHeader.biSize + m_pBI->bmiHeader.biSizeImage + GetPaletteSize();
}

DWORD KFCBitmap::LastByte( DWORD dwBitsPerPixel, DWORD dwPixels )
{
	 DWORD dwBits = dwBitsPerPixel * dwPixels;
	 DWORD numBytes  = dwBits / 8;
	 DWORD extraBits = dwBits - numBytes * 8;
	return (extraBits % 8) ? numBytes+1 : numBytes;
}


DWORD KFCBitmap::GetBytesPerLine( DWORD dwBitsPerPixel, DWORD dwWidth )
{
	DWORD dwBits = dwBitsPerPixel * dwWidth;

	if( (dwBits % 32) == 0 )
		return (dwBits/8);  // already DWORD aligned, no padding needed

	DWORD dwPadBits = 32 - (dwBits % 32);
	return (dwBits/8 + dwPadBits/8 + (((dwPadBits % 8) > 0) ? 1 : 0));
}

BOOL KFCBitmap::PadBits() 
{
	if( m_bIsPadded )
		return TRUE;

	// dwAdjust used when bits per pixel spreads over more than 1 byte
	DWORD dwAdjust = 1, dwOffset = 0, dwPadOffset=0;

	dwPadOffset = GetBytesPerLine(GetBitsPerPixel(), GetWidth());
	dwOffset = LastByte(GetBitsPerPixel(), GetWidth());

	if( dwPadOffset == dwOffset )
		return TRUE;

	BYTE * pTemp = new BYTE [GetWidth()*dwAdjust];
	if( !pTemp ) {
//		TRACELOG("KFCBitmap::PadBits(): could not allocate row of width %d.\n", GetWidth());
		return FALSE;
	}

	// enough space has already been allocated for the bit array to
	// include the padding, so we just need to shift rows around.
	// This will pad each "row" on a DWORD alignment.

	for( DWORD row = GetHeight()-1 ; row>0 ; --row ) {
		CopyMemory((void *)pTemp, ( void *)(m_pPixelBits + (row*dwOffset)), dwOffset );
		CopyMemory((void *)(m_pPixelBits + (row*dwPadOffset)), ( void *)pTemp, dwOffset);
	}
	//  delete [] pTemp;
	return TRUE;
}

BOOL KFCBitmap::UnPadBits() 
{
	if( ! m_bIsPadded )
		return TRUE;
	//DWORD dwAdjust = 1;
	//BOOL bIsOdd = FALSE;

	DWORD dwPadOffset = GetBytesPerLine(GetBitsPerPixel(), GetWidth());
	DWORD dwOffset = LastByte(GetBitsPerPixel(), GetWidth());

	BYTE * pTemp = new BYTE [dwOffset];
	if( !pTemp ) {
//		TRACELOG("KFCBitmap::UnPadBits() could not allocate row of width %d.\n", GetWidth());
		return FALSE;
	}

	// enough space has already been allocated for the bit array to
	// include the padding, so we just need to shift rows around.
	for( DWORD row=1 ; row < DWORD(GetHeight()); ++row ) {
		CopyMemory((void *)pTemp, ( void *)(m_pPixelBits + row*(dwPadOffset)), dwOffset);
		CopyMemory((void *)(m_pPixelBits + (row*dwOffset)), ( void *)pTemp, dwOffset);
	}

	delete [] pTemp;
	return TRUE;
}

int KFCBitmap::GetEffectWidth()
{
	return m_effWidth;
}

BOOL KFCBitmap::Inside(int x, int y)
{
	int w = GetWidth();
	int h = GetHeight();
	return (0<=y && y<h && 0<=x && x<w);
}

HBITMAP KFCBitmap::ClipBitmap(HBITMAP bmpSrc, int xSrc, int ySrc, int nWidth, int nHeight)
{
	HDC hDc = ::CreateCompatibleDC(NULL);
	::SelectObject(hDc, bmpSrc);

	HDC hdcDest = ::CreateCompatibleDC(hDc);
	HBITMAP ret = ::CreateCompatibleBitmap(hDc, nWidth, nHeight);

	::SelectObject(hdcDest, ret);

	::BitBlt(hdcDest, 0, 0, nWidth, nHeight, hDc, xSrc, ySrc, SRCCOPY);

	::DeleteDC(hdcDest);
	::DeleteDC(hDc);

	return ret;
}

//best performance !
HRGN KFCBitmap::BitmapToRegion (HBITMAP hBitmap, COLORREF cTransparentColor,COLORREF cTolerance)
{
	//DWORD dwStartTick = GetTickCount();
	//DWORD dwFinishTick;

	HRGN hRgn = NULL;

	if (hBitmap)
	{
		// Create a memory DC inside which we will scan the bitmap content
		HDC hMemDC = ::CreateCompatibleDC(NULL);
		if (hMemDC)
		{
			// Get bitmap size
			BITMAP bm;
			::GetObject(hBitmap, sizeof(bm), &bm);

			// Create a 32 bits depth bitmap and select it into the memory DC 
			BITMAPINFOHEADER RGB32BITSBITMAPINFO = {	
				sizeof(BITMAPINFOHEADER),	// biSize 
				bm.bmWidth,					// biWidth; 
				bm.bmHeight,				// biHeight; 
				1,							// biPlanes; 
				32,							// biBitCount 
				BI_RGB,						// biCompression; 
				0,							// biSizeImage; 
				0,							// biXPelsPerMeter; 
				0,							// biYPelsPerMeter; 
				0,							// biClrUsed; 
				0							// biClrImportant; 
			};
			VOID * pbits32; 
			HBITMAP hbm32 = ::CreateDIBSection(hMemDC, (BITMAPINFO *)&RGB32BITSBITMAPINFO, DIB_RGB_COLORS, &pbits32, NULL, 0);
			if (hbm32)
			{
				HBITMAP holdBmp = (HBITMAP)::SelectObject(hMemDC, hbm32);

				// Create a DC just to copy the bitmap into the memory DC
				HDC hDC = ::CreateCompatibleDC(hMemDC);
				if (hDC)
				{
					// Get how many bytes per row we have for the bitmap bits (rounded up to 32 bits)
					BITMAP bm32;
					::GetObject(hbm32, sizeof(bm32), &bm32);
					while (bm32.bmWidthBytes % 4)
						bm32.bmWidthBytes++;

					// Copy the bitmap into the memory DC
					HBITMAP holdBmp = (HBITMAP)::SelectObject(hDC, hBitmap);
					::BitBlt(hMemDC, 0, 0, bm.bmWidth, bm.bmHeight, hDC, 0, 0, SRCCOPY);

					// For better performances, we will use the ExtCreateRegion() function to create the
					// region. This function take a RGNDATA structure on entry. We will add rectangles by
					// amount of ALLOC_UNIT number in this structure.
#define ALLOC_UNIT	100
					DWORD maxRects = ALLOC_UNIT;
					HANDLE hData = ::GlobalAlloc(GMEM_MOVEABLE, sizeof(RGNDATAHEADER) + (sizeof(RECT) * maxRects));
					RGNDATA *pData = (RGNDATA *)::GlobalLock(hData);
					pData->rdh.dwSize = sizeof(RGNDATAHEADER);
					pData->rdh.iType = RDH_RECTANGLES;
					pData->rdh.nCount = pData->rdh.nRgnSize = 0;
					::SetRect(&pData->rdh.rcBound, MAXLONG, MAXLONG, 0, 0);

					// Keep on hand highest and lowest values for the "transparent" pixels
					BYTE lr = GetRValue(cTransparentColor);
					BYTE lg = GetGValue(cTransparentColor);
					BYTE lb = GetBValue(cTransparentColor);
					BYTE hr = min(0xff, lr + GetRValue(cTolerance));
					BYTE hg = min(0xff, lg + GetGValue(cTolerance));
					BYTE hb = min(0xff, lb + GetBValue(cTolerance));

					// Scan each bitmap row from bottom to top (the bitmap is inverted vertically)
					BYTE *p32 = (BYTE *)bm32.bmBits + (bm32.bmHeight - 1) * bm32.bmWidthBytes;
					for (int y = 0; y < bm.bmHeight; y++)
					{
						// Scan each bitmap pixel from left to right
						for (int x = 0; x < bm.bmWidth; x++)
						{
							// Search for a continuous range of "non transparent pixels"
							int x0 = x;
							LONG *p = (LONG *)p32 + x;
							while (x < bm.bmWidth)
							{
								BYTE b = GetRValue(*p);
								if (b >= lr && b <= hr)
								{
									b = GetGValue(*p);
									if (b >= lg && b <= hg)
									{
										b = GetBValue(*p);
										if (b >= lb && b <= hb)
											// This pixel is "transparent"
											break;
									}
								}
								p++;
								x++;
							}

							if (x > x0)
							{
								// Add the pixels (x0, y) to (x, y+1) as a new rectangle in the region
								if (pData->rdh.nCount >= maxRects)
								{
									::GlobalUnlock(hData);
									maxRects += ALLOC_UNIT;
									hData = ::GlobalReAlloc(hData, sizeof(RGNDATAHEADER) + (sizeof(RECT) * maxRects), GMEM_MOVEABLE);
									pData = (RGNDATA *)::GlobalLock(hData);
								}
								RECT *pr = (RECT *)&pData->Buffer;
								::SetRect(&pr[pData->rdh.nCount], x0, y, x, y+1);
								if (x0 < pData->rdh.rcBound.left)
									pData->rdh.rcBound.left = x0;
								if (y < pData->rdh.rcBound.top)
									pData->rdh.rcBound.top = y;
								if (x > pData->rdh.rcBound.right)
									pData->rdh.rcBound.right = x;
								if (y+1 > pData->rdh.rcBound.bottom)
									pData->rdh.rcBound.bottom = y+1;
								pData->rdh.nCount++;

								// On Windows98, ExtCreateRegion() may fail if the number of rectangles is too
								// large (ie: > 4000). Therefore, we have to create the region by multiple steps.
								if (pData->rdh.nCount == 2000)
								{
									HRGN h = ::ExtCreateRegion(NULL, sizeof(RGNDATAHEADER) + (sizeof(RECT) * maxRects), pData);
									if (hRgn)
									{
										::CombineRgn(hRgn, hRgn, h, RGN_OR);
										::DeleteObject(h);
									}
									else
										hRgn = h;
									pData->rdh.nCount = 0;
									::SetRect(&pData->rdh.rcBound, MAXLONG, MAXLONG, 0, 0);
								}
							}
						}

						// Go to next row (remember, the bitmap is inverted vertically)
						p32 -= bm32.bmWidthBytes;
					}

					// Create or extend the region with the remaining rectangles
					HRGN h = ::ExtCreateRegion(NULL, sizeof(RGNDATAHEADER) + (sizeof(RECT) * maxRects), pData);
					if (hRgn)
					{
						::CombineRgn(hRgn, hRgn, h, RGN_OR);
						::DeleteObject(h);
					}
					else
						hRgn = h;

					// Clean up
					::GlobalFree(hData);
					::SelectObject(hDC, holdBmp);
					::DeleteDC(hDC);
				}

				::DeleteObject(::SelectObject(hMemDC, holdBmp));
			}

			::DeleteDC(hMemDC);
		}	
	}
	//dwFinishTick = GetTickCount();
#ifdef DEBUG
	//  CHAR str[200];
	//  wsprintf(str,"BitmapToRegion Function : Elapsed times = %ld \n",dwFinishTick - dwStartTick);
	//  OutputDebugString(str); 
#endif
	return hRgn;
}

BOOL KFCBitmap::RegionToFile(HRGN hRgn,LPSTR szFilename)
{
	if(szFilename == NULL || lstrlen((LPCTSTR)szFilename) < 1)
		return FALSE;
	// char *MSGCAPTION="Save RGN";

	HGLOBAL hmem;
	RGNDATA *pRd;
	int nSize;

	// open file
	HANDLE hFile = CreateFile((LPCTSTR)szFilename, GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, 0, NULL);
	if(INVALID_HANDLE_VALUE != hFile)
	{
		nSize = GetRegionData(hRgn, NULL, 0);
		////assert (nSize);
		if ((hmem=GlobalAlloc(GHND, nSize)) == NULL){
//			TRACELOG ("failed to alloc memory\n");
			return FALSE;
		}
		if ((pRd=(RGNDATA *)GlobalLock (hmem)) == NULL){
///			TRACELOG ("failed to lock memory\n");
			return FALSE;
		}
		//get the region data structure
		GetRegionData(hRgn, nSize, pRd);
		// Set dimensions of bounding region rectangle
		//GetRgnBox(hRgn, &rcSkin); 
		DWORD nWritten;
		BOOL bWrite;
		bWrite = ::WriteFile(hFile,pRd,nSize, &nWritten, NULL);

		GlobalUnlock (hmem);
		GlobalFree (hmem);
		CloseHandle(hFile);
	}
	return TRUE;
}

HRGN KFCBitmap::FileToRegion(LPSTR szFilename)
{
	HRGN hRgn = NULL;
	//try
	//{
		//ructing these file objects doesn't open them
		// open the source file for reading
		HANDLE hFile = CreateFile((LPCTSTR)szFilename, GENERIC_READ,FILE_SHARE_READ, NULL, OPEN_EXISTING, 0, NULL);
		if(INVALID_HANDLE_VALUE != hFile)
		{
			// Get size of region file
			ULONGLONG fileLength;
			ULARGE_INTEGER liSize;
			liSize.LowPart = ::GetFileSize(hFile, &liSize.HighPart);
			fileLength = liSize.QuadPart;

			// Create buffer to match region file size
			TCHAR *szBuffer = new TCHAR[(UINT)fileLength];
			UINT  nActual = 0; 
			// Set pointer to beginning of file
			LARGE_INTEGER liOff;
			liOff.QuadPart = 0;
			liOff.LowPart = ::SetFilePointer(hFile, liOff.LowPart, &liOff.HighPart,FILE_BEGIN);
			//liOff.QuadPart is new pointer

			// Read region file into buffer
			BOOL bRead;
			DWORD dwBytesRead = 0;
			bRead = ReadFile(hFile,szBuffer, (DWORD)fileLength, &dwBytesRead, NULL);
			nActual = dwBytesRead;
			// Close source file
			CloseHandle(hFile);

			// Create region object locally on heap because this method may be called a lot and CRgn objects can cause memory leaks
			hRgn = ExtCreateRegion(NULL, nActual,(LPRGNDATA) szBuffer);
			// You MUST release allocated memory as follows!
			delete [] szBuffer;
		}
	//}
	//catch( ... ) {}
	return hRgn;
}

int KFCBitmap::GetIndex(int x, int y)
{
	int depth = GetBitsPerPixel();
	if (!Inside(x, y) || (depth > 8)) return -1;

	BYTE * ImagePointer = m_pPixelBits + m_effWidth * y + (x * depth >> 3);
	int index = (int)(*ImagePointer);
	return index;
}

//get rgb in palette if exist palette ( depth < 8)
BOOL KFCBitmap::GetPalRGB( int index, unsigned char *red, unsigned char *green, unsigned char *blue)
{
	if (index < 0 || index > 255)
		return FALSE;

	PALETTEENTRY entry;
	if(::GetPaletteEntries(m_hPal, index, 1, &entry))
	{
		*red = entry.peRed;
		*green = entry.peGreen;
		*blue = entry.peBlue;
		return TRUE;
	} else
		return FALSE;
}

int KFCBitmap::GetPalIndex( unsigned char red,unsigned char green,unsigned char blue)
{
	return ::GetNearestPaletteIndex(m_hPal, RGB(red, green, blue));
}

BOOL KFCBitmap::GetRGB(int x, int y, byte* r, byte* g, byte* b,byte*a)
{
	if (!Inside(x, y)) return FALSE;

	if (m_hPal) {
		return GetPalRGB(GetIndex(x, y), r, g, b);
		/*	 PALETTEENTRY entry;
		::GetPaletteEntries(m_hPal, GetIndex(x, y), 1, &entry);
		*r = entry.peRed;
		*g = entry.peGreen;
		*b = entry.peBlue;  */
	} else {
		int depth = GetBitsPerPixel();
		BYTE * ImagePointer = m_pPixelBits + m_effWidth * y + (x * depth >> 3);
		DWORD *pc = (DWORD *)ImagePointer;
		DWORD c = *pc;
		RGBQUAD rgba;
		memcpy(&rgba,&c,sizeof(RGBQUAD));
		
		if((depth >> 3) >= 4){
			if(a)
				*a = ImagePointer[0];
			*b = ImagePointer[1];
			*g = ImagePointer[2];
			*r = ImagePointer[3];
		}
		else{
			if(a)
				*a = 0xff;
			*b = ImagePointer[0];
			*g = ImagePointer[1];
			*r = ImagePointer[2];
		}
	}
	return TRUE;
}
#pragma warning(push)
#pragma warning (disable:4244)

BOOL KFCBitmap::SetIndex(int x, int y, int index)
{
	int depth = GetBitsPerPixel();
	if (!Inside(x, y) || (depth > 8)) return FALSE;

	BYTE * ImagePointer = m_pPixelBits + m_effWidth * y + (x * depth >> 3);
	*ImagePointer = index;

	return TRUE;
}
#pragma warning(pop)

BOOL KFCBitmap::SetRGB(int x, int y, byte r, byte g, byte b)
{
	if (!Inside(x, y)) return FALSE;

	if (m_hPal)
	{
		SetIndex(x, y,GetPalIndex(r, g, b));

	} else {
		int depth = GetBitsPerPixel();
		BYTE * ImagePointer = m_pPixelBits + m_effWidth * y + (x * depth >> 3);

		if((depth >> 3) >= 4){//32bpp
			ImagePointer[1] = b;
			ImagePointer[2] = g;
			ImagePointer[3] = r;
		}
		else{
			ImagePointer[0] = b;
			ImagePointer[1] = g;
			ImagePointer[2] = r;
		}
	}
	return TRUE;
}

//sample for usage.
void KFCBitmap::example(HDC hDC,LPCTSTR szImgFile)
{
	HBITMAP m_gbitmap = 0;
	HBITMAP m_clipbmp = 0;
	
	KFCBitmap gsb;
	//Load
	KFCBitmap sb;
	m_gbitmap = gsb.Load(szImgFile);// you may call other load function like Load2,Load3 if you hope.
	m_clipbmp = gsb.ClipBitmap(m_gbitmap,0,0,100,100);//cut region

	//Draw Test

	KFCBitmap sb2(m_gbitmap);//attach external HBITMAP
	KFCBitmap sb3(m_clipbmp);//attach external HBITMAP
	RECT rectimg,rectDC,rectDC2;
	SetRect(&rectimg,0,0,-1,-1);
	SetRect(&rectDC,0,40,-1,-1);
	SetRect(&rectDC2,0,100,-1,-1);
	gsb.DrawNormal(hDC,rectDC,rectimg);
	sb2.DrawNormal(hDC,rectDC,rectimg);
	sb3.DrawTransparent(hDC,RGB(255,0,255),rectDC2,rectimg);
	//If you ready to using DrawBitmap function,i recommend to you using Load3() to load image.
	//it is independent working functions from inside this class's others.
}

Download New Updated Class: