forked from misakamm/xege
-
Notifications
You must be signed in to change notification settings - Fork 50
/
Copy pathimage.cpp
3345 lines (2957 loc) · 118 KB
/
image.cpp
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
/*
* EGE (Easy Graphics Engine)
* filename image.cpp
本文件集中所有对image基本操作的接口和类定义
*/
#ifndef _CRT_SECURE_NO_WARNINGS
#define _CRT_SECURE_NO_WARNINGS
#endif
#ifndef _CRT_SECURE_NO_DEPRECATE
#define _CRT_SECURE_NO_DEPRECATE
#endif
#include "ege_head.h"
#include "ege_common.h"
#include "ege_dllimport.h"
#include "image.h"
// #ifdef _ITERATOR_DEBUG_LEVEL
// #undef _ITERATOR_DEBUG_LEVEL
// #endif
#include <png.h>
#include <math.h>
#include <limits.h>
namespace ege
{
void IMAGE::reset()
{
m_initflag = IMAGE_INIT_FLAG;
m_hDC = NULL;
m_hBmp = NULL;
m_width = 0;
m_height = 0;
m_pBuffer = NULL;
m_linecolor = 0;
m_fillcolor = 0;
m_textcolor = 0;
m_bk_color = 0;
m_aa = false;
memset(&m_vpt, 0, sizeof(m_vpt));
memset(&m_texttype, 0, sizeof(m_texttype));
memset(&m_linestyle, 0, sizeof(m_linestyle));
m_linewidth = 0.0f;
m_linestartcap = LINECAP_FLAT;
m_lineendcap = LINECAP_FLAT;
m_linejoin = LINEJOIN_MITER;
m_linejoinmiterlimit = 10.0f;
m_texture = NULL;
#ifdef EGE_GDIPLUS
m_graphics = NULL;
m_pen = NULL;
m_brush = NULL;
#endif
}
/**
* 构造宽高为 width x height 的图像。
* @param width
* @param height
* @note: 创建的图像内容未定义,但经检测像素值均为 0。
*/
void IMAGE::construct(int width, int height)
{
HDC refDC = NULL;
if (graph_setting.hwnd) {
refDC = ::GetDC(graph_setting.hwnd);
}
dll::loadDllsIfNot();
gdiplusinit();
reset();
initimage(refDC, width, height);
setdefaultattribute();
if (refDC) {
::ReleaseDC(graph_setting.hwnd, refDC);
}
}
/**
* 构造宽高为 width x height 的图像,将 color 设为背景色并以 color 填充整个图像。
* @param width
* @param height
* @param color
*/
void IMAGE::construct(int width, int height, color_t color)
{
construct(width, height);
setbkcolor_f(color, this);
cleardevice(this);
}
IMAGE::IMAGE()
{
construct(1, 1, BLACK);
}
IMAGE::IMAGE(int width, int height)
{
// 截止到 0
if (width < 0) {
width = 0;
}
if (height < 0) {
height = 0;
}
construct(width, height);
}
IMAGE::IMAGE(int width, int height, color_t color)
{
// 截止到 0
if (width < 0) {
width = 0;
}
if (height < 0) {
height = 0;
}
construct(width, height, color);
}
IMAGE::IMAGE(const IMAGE& img)
{
reset();
initimage(img.m_hDC, img.m_width, img.m_height);
setdefaultattribute();
BitBlt(m_hDC, 0, 0, img.m_width, img.m_height, img.m_hDC, 0, 0, SRCCOPY);
}
IMAGE::~IMAGE()
{
gentexture(false);
deleteimage();
}
void IMAGE::inittest(const WCHAR* strCallFunction) const
{
if (m_initflag != IMAGE_INIT_FLAG) {
WCHAR str[60];
wsprintfW(str, L"Fatal error: read/write at 0x%p. At function '%s'", this, strCallFunction);
MessageBoxW(graph_setting.hwnd, str, L"EGE ERROR message", MB_ICONSTOP);
ExitProcess((UINT)grError);
}
}
void IMAGE::gentexture(bool gen)
{
if (!gen) {
if (m_texture != NULL) {
delete (Gdiplus::Bitmap*)m_texture;
m_texture = NULL;
}
} else {
if (m_texture != NULL) {
gentexture(false);
}
Gdiplus::Bitmap* bitmap =
new Gdiplus::Bitmap(getwidth(), getheight(), getwidth() * 4, PixelFormat32bppARGB, (BYTE*)getbuffer());
m_texture = bitmap;
}
}
int IMAGE::deleteimage()
{
#ifdef EGE_GDIPLUS
if (NULL != m_graphics) {
delete m_graphics;
}
m_graphics = NULL;
if (NULL != m_pen) {
delete m_pen;
}
m_pen = NULL;
if (NULL != m_brush) {
delete m_brush;
}
m_brush = NULL;
#endif
HBITMAP hbmp = (HBITMAP)GetCurrentObject(m_hDC, OBJ_BITMAP);
HBRUSH hbr = (HBRUSH)GetCurrentObject(m_hDC, OBJ_BRUSH);
HPEN hpen = (HPEN)GetCurrentObject(m_hDC, OBJ_PEN);
HFONT hfont = (HFONT)GetCurrentObject(m_hDC, OBJ_FONT);
DeleteDC(m_hDC);
m_hDC = NULL;
DeleteObject(hbmp);
DeleteObject(hbr);
DeleteObject(hpen);
DeleteObject(hfont);
return 0;
}
HBITMAP newbitmap(int width, int height, PDWORD* p_bmp_buf)
{
HBITMAP bitmap;
BITMAPINFO bmi = {{0}};
PDWORD bmp_buf;
// 截止到 1
if (width < 1) {
width = 1;
}
if (height < 1) {
height = 1;
}
bmi.bmiHeader.biSize = sizeof(bmi.bmiHeader);
bmi.bmiHeader.biWidth = width;
bmi.bmiHeader.biHeight = -height;
bmi.bmiHeader.biPlanes = 1;
bmi.bmiHeader.biBitCount = 32;
bmi.bmiHeader.biSizeImage = width * height * 4;
bitmap = CreateDIBSection(NULL, &bmi, DIB_RGB_COLORS, (VOID**)&bmp_buf, NULL, 0);
if (p_bmp_buf) {
*p_bmp_buf = bmp_buf;
}
return bitmap;
}
void IMAGE::initimage(HDC refDC, int width, int height)
{
HDC dc = CreateCompatibleDC(refDC);
PDWORD bmp_buf;
HBITMAP bitmap = newbitmap(width, height, &bmp_buf);
if (bitmap == NULL) {
internal_panic(L"Fatal Error: Create Bitmap fail in 'IMAGE::initimage'");
}
::SelectObject(dc, bitmap);
m_hDC = dc;
m_hBmp = bitmap;
m_width = width;
m_height = height;
m_pBuffer = bmp_buf;
setviewport(0, 0, m_width, m_height, 1, this);
}
void IMAGE::setdefaultattribute()
{
setlinecolor(initial_line_color, this);
settextcolor(initial_text_color, this);
setbkcolor_f(initial_bk_color, this);
SetBkMode(m_hDC, OPAQUE);
setfillstyle(SOLID_FILL, initial_fill_color, this);
setlinestyle(PS_SOLID, 0, 1, this);
settextjustify(LEFT_TEXT, TOP_TEXT, this);
setfont(16, 0, "SimSun", this);
enable_anti_alias(false);
}
#ifdef EGE_GDIPLUS
Gdiplus::Graphics* IMAGE::getGraphics()
{
if (NULL == m_graphics) {
m_graphics = new Gdiplus::Graphics(m_hDC);
m_graphics->SetPixelOffsetMode(Gdiplus::PixelOffsetModeHalf);
m_graphics->SetSmoothingMode(m_aa ? Gdiplus::SmoothingModeAntiAlias : Gdiplus::SmoothingModeNone);
m_graphics->SetTextRenderingHint(
m_aa ? Gdiplus::TextRenderingHintAntiAlias : Gdiplus::TextRenderingHintSystemDefault);
}
return m_graphics;
}
Gdiplus::Pen* IMAGE::getPen()
{
if (NULL == m_pen) {
m_pen = new Gdiplus::Pen(m_linecolor, m_linewidth);
m_pen->SetDashStyle(linestyle_to_dashstyle(m_linestyle.linestyle));
}
return m_pen;
}
Gdiplus::Brush* IMAGE::getBrush()
{
if (NULL == m_brush) {
m_brush = new Gdiplus::SolidBrush(m_fillcolor);
}
return m_brush;
}
void IMAGE::set_pattern(Gdiplus::Brush* brush)
{
if (NULL != m_brush) {
delete m_brush;
}
m_brush = brush;
}
#endif
void IMAGE::enable_anti_alias(bool enable)
{
m_aa = enable;
#ifdef EGE_GDIPLUS
if (NULL != m_graphics) {
m_graphics->SetSmoothingMode(m_aa ? Gdiplus::SmoothingModeAntiAlias : Gdiplus::SmoothingModeNone);
m_graphics->SetTextRenderingHint(
m_aa ? Gdiplus::TextRenderingHintAntiAlias : Gdiplus::TextRenderingHintSystemDefault);
}
#endif
}
int IMAGE::resize_f(int width, int height)
{
inittest(L"IMAGE::resize_f");
// 截止到 0
if (width < 0) {
width = 0;
}
if (height < 0) {
height = 0;
}
if (width == m_width && height == m_height) {
setviewport(0, 0, m_width, m_height, 1, this);
return 0;
}
PDWORD bmp_buf;
HBITMAP bitmap = newbitmap(width, height, &bmp_buf);
HBITMAP old_bitmap = (HBITMAP)SelectObject(this->m_hDC, bitmap);
DeleteObject(old_bitmap);
m_hBmp = bitmap;
m_width = width;
m_height = height;
m_pBuffer = bmp_buf;
SelectClipRgn(this->m_hDC, NULL);
// BITMAP 更换后需重新创建 Graphics 对象(否则会在已销毁的 old_bitmap 上绘制,引发异常)
if (m_graphics != NULL) {
Gdiplus::Graphics* newGraphics = recreateGdiplusGraphics(m_hDC, m_graphics);
delete m_graphics;
m_graphics = newGraphics;
}
setviewport(0, 0, m_width, m_height, 1, this);
return 0;
}
int IMAGE::resize(int width, int height)
{
inittest(L"IMAGE::resize");
int ret = this->resize_f(width, height);
cleardevice(this);
return ret;
}
IMAGE& IMAGE::operator=(const IMAGE& img)
{
inittest(L"IMAGE::operator=");
this->copyimage(&img);
return *this;
}
void IMAGE::copyimage(PCIMAGE pSrcImg)
{
inittest(L"IMAGE::copyimage");
PCIMAGE img = CONVERT_IMAGE_CONST(pSrcImg);
this->getimage(img, 0, 0, img->getwidth(), img->getheight());
CONVERT_IMAGE_END;
}
int IMAGE::getimage(PCIMAGE pSrcImg, int xSrc, int ySrc, int srcWidth, int srcHeight)
{
inittest(L"IMAGE::getimage");
PCIMAGE img = CONVERT_IMAGE_CONST(pSrcImg);
this->resize_f(srcWidth, srcHeight);
BitBlt(this->m_hDC, 0, 0, srcWidth, srcHeight, img->m_hDC, xSrc, ySrc, SRCCOPY);
CONVERT_IMAGE_END;
return grOk;
}
int IMAGE::getimage(int xSrc, int ySrc, int srcWidth, int srcHeight)
{
PIMAGE img = CONVERT_IMAGE_CONST(0);
this->getimage(img, xSrc, ySrc, srcWidth, srcHeight);
CONVERT_IMAGE_END;
return grOk;
}
void IMAGE::putimage(
PIMAGE imgDest, int xDest, int yDest, int widthDest, int heightDest, int xSrc, int ySrc, DWORD dwRop) const
{
inittest(L"IMAGE::putimage");
PIMAGE img = CONVERT_IMAGE(imgDest);
BitBlt(img->m_hDC, xDest, yDest, widthDest, heightDest, m_hDC, xSrc, ySrc, dwRop);
CONVERT_IMAGE_END;
}
void IMAGE::putimage(PIMAGE imgDest, int xDest, int yDest, DWORD dwRop) const
{
this->putimage(imgDest, xDest, yDest, m_width, m_height, 0, 0, dwRop);
}
void IMAGE::putimage(int xDest, int yDest, int widthDest, int heightDest, int xSrc, int ySrc, DWORD dwRop) const
{
PIMAGE img = CONVERT_IMAGE(0);
this->putimage(img, xDest, yDest, widthDest, heightDest, xSrc, ySrc, dwRop);
CONVERT_IMAGE_END;
}
void IMAGE::putimage(int xDest, int yDest, DWORD dwRop) const
{
PIMAGE img = CONVERT_IMAGE(0);
this->putimage(img, xDest, yDest, dwRop);
CONVERT_IMAGE_END;
}
int IMAGE::getimage(const char* filename, int zoomWidth, int zoomHeight)
{
const std::wstring& filename_w = mb2w(filename);
return getimage(filename_w.c_str(), zoomWidth, zoomHeight);
}
int getimage_from_bitmap(PIMAGE pimg, Gdiplus::Bitmap& bitmap)
{
// 将图像尺寸调整至和 bitmap 一致
int width = bitmap.GetWidth();
int height = bitmap.GetHeight();
resize_f(pimg, width, height);
// 设置外部缓冲区属性,指向图像缓冲区首地址
Gdiplus::BitmapData bitmapData;
bitmapData.Width = width;
bitmapData.Height = height;
bitmapData.Stride = width * sizeof(color_t); // 至下一行像素的偏移量(字节)
bitmapData.PixelFormat = PixelFormat32bppARGB; // 像素颜色格式: 32 位 ARGB
bitmapData.Scan0 = getbuffer(pimg); // 图像首行像素的首地址
// 读取区域设置为整个图像
Gdiplus::Rect rect(0, 0, width, height);
// 模式: 仅读取图像数据, 缓冲区由用户分配
int imageLockMode = Gdiplus::ImageLockModeRead | Gdiplus::ImageLockModeUserInputBuf;
//读取 Bitmap 图像内容,以 32 位 ARGB 的像素格式写入缓冲区
bitmap.LockBits(&rect, imageLockMode, PixelFormat32bppARGB, &bitmapData);
// 解除锁定(如果设置了 ImageLockModeWrite 模式,还会将缓冲区内容复制到 Bitmap)
bitmap.UnlockBits(&bitmapData);
return grOk;
}
int IMAGE::getimage(const wchar_t* filename, int zoomWidth, int zoomHeight)
{
(void)zoomWidth, (void)zoomHeight; // ignore
inittest(L"IMAGE::getimage");
{
int ret = getimage_pngfile(this, filename);
// grIOerror means it's not a png file
if (ret != grIOerror) {
return ret;
}
}
OLECHAR wszPath[MAX_PATH * 2 + 1];
WCHAR szPath[MAX_PATH * 2 + 1] = L"";
if (wcsstr(filename, L"http://")) {
lstrcpyW(szPath, filename);
} else if (filename[1] == ':') {
lstrcpyW(szPath, filename);
} else {
GetCurrentDirectoryW(MAX_PATH * 2, szPath);
lstrcatW(szPath, L"\\");
lstrcatW(szPath, filename);
}
lstrcpyW(wszPath, szPath);
Gdiplus::Bitmap bitmap(wszPath);
if (bitmap.GetLastStatus() != Gdiplus::Ok) {
return grIOerror;
}
getimage_from_bitmap(this, bitmap);
if (bitmap.GetLastStatus() != Gdiplus::Ok) {
return grError;
}
return grOk;
}
int IMAGE::saveimage(const char* filename, bool withAlphaChannel) const
{
return saveimage(mb2w(filename).c_str(), withAlphaChannel);
}
int IMAGE::saveimage(const wchar_t* filename, bool withAlphaChannel) const
{
return ege::saveimage(this, filename, withAlphaChannel);
}
void getimage_from_png_struct(PIMAGE self, void* vpng_ptr, void* vinfo_ptr)
{
png_structp png_ptr = (png_structp)vpng_ptr;
png_infop info_ptr = (png_infop)vinfo_ptr;
#if defined(PNG_SKIP_sRGB_CHECK_PROFILE) && defined(PNG_SET_OPTION_SUPPORTED)
png_set_option(png_ptr, PNG_SKIP_sRGB_CHECK_PROFILE,
PNG_OPTION_ON);
#endif
// 读取 PNG 文件信息, 存入 info_ptr 中
png_read_info(png_ptr, info_ptr);
const png_byte color_type = png_get_color_type(png_ptr, info_ptr);
const png_byte bit_depth = png_get_bit_depth(png_ptr, info_ptr); // 每通道位深度
// 将颜色类型转为 RGB 或 RGBA
if (color_type == PNG_COLOR_TYPE_PALETTE) {
png_set_palette_to_rgb(png_ptr);
} else if ((color_type == PNG_COLOR_TYPE_GRAY) && (color_type == PNG_COLOR_TYPE_GRAY_ALPHA)) {
png_set_gray_to_rgb(png_ptr);
}
// 将位深度设置为每通道 8 bit
// (PNG 格式规定,RGB(RGBA) 位深度为 8 或 16,不会低于 8)
if (bit_depth == 16) {
png_set_strip_16(png_ptr); // bit depth 16 to 8
}
// 补齐 alpha 通道
if ((color_type != PNG_COLOR_TYPE_RGB_ALPHA) && (color_type != PNG_COLOR_TYPE_GRAY_ALPHA)) {
// 若在 tRNS 块中存在透明度信息则将其转为 alpha 通道
if (png_get_valid(png_ptr, info_ptr, PNG_INFO_tRNS)) {
png_set_tRNS_to_alpha(png_ptr);
} else {
// 添加 alpha 通道(最高字节)并以 0xFF 填充
png_set_add_alpha(png_ptr, 0xFF, PNG_FILLER_AFTER);
}
}
// 调整通道存储顺序,字节从低到高依次为 B, G, R, A
png_set_bgr(png_ptr);
// 根据以上设置的目标格式更新 png_info 结构
png_read_update_info(png_ptr, info_ptr);
// 经过以上设置,像素格式为 ARGB (字节顺序从低至高依次为 B, G, R, A), 位深度为 8 (每通道)
const png_uint_32 width = png_get_image_width(png_ptr, info_ptr);
const png_uint_32 height = png_get_image_height(png_ptr, info_ptr);
// 将图像宽高调整至与 PNG 图片一致
self->resize_f((int)width, (int)height);
// 创建 png_bytep 数组,指向图像缓冲区中每一行像素的首地址
const png_bytepp row_pointers = new png_bytep[height];
color_t* buffer = (color_t*)self->m_pBuffer;
for (png_uint_32 i = 0; i < height; i++) {
row_pointers[i] = (png_bytep)(&buffer[i * width]);
}
// 读取图像数据,存入 row_pointers 所指向的内存区域
png_read_image(png_ptr, row_pointers);
delete[] row_pointers;
}
int IMAGE::getpngimg(FILE* fp)
{
png_structp png_ptr;
png_infop info_ptr;
{
char header[16];
uint32_t number = 8;
fread(header, 1, number, fp);
int isn_png = png_sig_cmp((png_const_bytep)header, 0, number);
if (isn_png) {
return grIOerror;
}
fseek(fp, 0, SEEK_SET);
}
png_ptr = png_create_read_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL);
if (png_ptr == NULL) {
return grAllocError;
}
info_ptr = png_create_info_struct(png_ptr);
if (info_ptr == NULL) {
png_destroy_read_struct(&png_ptr, NULL, NULL);
return grAllocError;
}
png_init_io(png_ptr, fp);
getimage_from_png_struct(this, png_ptr, info_ptr);
png_destroy_read_struct(&png_ptr, &info_ptr, NULL);
return grOk;
}
int IMAGE::savepngimg(FILE* fp, bool withAlphaChannel) const
{
unsigned long i, j;
png_structp png_ptr;
png_infop info_ptr;
png_colorp palette;
png_byte* image;
png_bytep* row_pointers;
png_ptr = png_create_write_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL);
uint32_t pixelsize = withAlphaChannel ? 4 : 3;
uint32_t width = m_width, height = m_height;
if (png_ptr == NULL) {
return -1;
}
info_ptr = png_create_info_struct(png_ptr);
if (info_ptr == NULL) {
png_destroy_write_struct(&png_ptr, NULL);
return -1;
}
/*if (setjmp(png_jmpbuf(png_ptr)))
{
png_destroy_write_struct(&png_ptr, &info_ptr);
return -1;
}// */
png_init_io(png_ptr, fp);
png_set_IHDR(png_ptr, info_ptr, width, height, 8, withAlphaChannel ? PNG_COLOR_TYPE_RGBA : PNG_COLOR_TYPE_RGB,
PNG_INTERLACE_NONE, PNG_COMPRESSION_TYPE_DEFAULT, PNG_FILTER_TYPE_DEFAULT);
palette = (png_colorp)png_malloc(png_ptr, PNG_MAX_PALETTE_LENGTH * sizeof(png_color));
png_set_PLTE(png_ptr, info_ptr, palette, PNG_MAX_PALETTE_LENGTH);
png_write_info(png_ptr, info_ptr);
png_set_packing(png_ptr);
image = (png_byte*)malloc(width * height * pixelsize * sizeof(png_byte) + 4);
if (image == NULL) {
png_destroy_write_struct(&png_ptr, &info_ptr);
return -1;
}
row_pointers = (png_bytep*)malloc(height * sizeof(png_bytep));
if (row_pointers == NULL) {
png_destroy_write_struct(&png_ptr, &info_ptr);
free(image);
image = NULL;
return -1;
}
for (i = 0; i < height; i++) {
for (j = 0; j < width; ++j) {
(DWORD&)image[(i * width + j) * pixelsize] = RGBTOBGR(m_pBuffer[i * width + j]);
}
row_pointers[i] = (png_bytep)image + i * width * pixelsize;
}
png_write_image(png_ptr, row_pointers);
png_write_end(png_ptr, info_ptr);
png_free(png_ptr, palette);
palette = NULL;
png_destroy_write_struct(&png_ptr, &info_ptr);
free(row_pointers);
row_pointers = NULL;
free(image);
image = NULL;
return 0;
}
struct MemCursor
{
png_const_bytep data;
png_size_t size;
png_size_t cur;
};
static void read_data_from_MemCursor(png_structp png_ptr, png_bytep outBytes, png_size_t byteCountToRead)
{
MemCursor& cursor = *(MemCursor*)png_get_io_ptr(png_ptr);
png_size_t count = MIN(cursor.size - cursor.cur, byteCountToRead);
memcpy(outBytes, cursor.data + cursor.cur, count);
cursor.cur += count;
}
inline int getimage_from_resource(PIMAGE self, HRSRC hrsrc)
{
if (hrsrc) {
HGLOBAL hg = LoadResource(0, hrsrc);
DWORD dwSize = SizeofResource(0, hrsrc);
LPVOID pvRes = LockResource(hg);
if (dwSize >= 8 && png_check_sig((png_const_bytep)pvRes, 8)) {
png_structp png_ptr;
png_infop info_ptr;
MemCursor cursor;
cursor.data = (png_const_bytep)pvRes;
cursor.size = dwSize;
cursor.cur = 0;
png_ptr = png_create_read_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL);
if (png_ptr == NULL) {
return grAllocError;
}
info_ptr = png_create_info_struct(png_ptr);
if (info_ptr == NULL) {
png_destroy_read_struct(&png_ptr, NULL, NULL);
return grAllocError;
}
png_set_read_fn(png_ptr, &cursor, read_data_from_MemCursor);
getimage_from_png_struct(self, png_ptr, info_ptr);
png_destroy_read_struct(&png_ptr, &info_ptr, NULL);
} else {
HGLOBAL hGlobal = GlobalAlloc(GMEM_MOVEABLE, dwSize);
LPVOID pvData;
IStream* pStm;
if (hGlobal == NULL || (pvData = GlobalLock(hGlobal)) == NULL) {
return grAllocError;
}
memcpy(pvData, pvRes, dwSize);
GlobalUnlock(hGlobal);
if (S_OK != dll::CreateStreamOnHGlobal(hGlobal, TRUE, &pStm)) {
return grNullPointer;
}
Gdiplus::Bitmap bitmap(pStm);
int status = bitmap.GetLastStatus();
if (status != Gdiplus::Ok) {
return grError;
}
getimage_from_bitmap(self, bitmap);
// GlobalFree 不能在 Bitmap 读取完成之前调用
// 否则 Bitmap::LockBits() 返回 Win32Error 错误码
GlobalFree(hGlobal);
}
return grOk;
}
return grIOerror;
}
int IMAGE::getimage(const char* resType, const char* resName, int zoomWidth, int zoomHeight)
{
const std::wstring& pResType_w = mb2w(resType);
const std::wstring& pResName_w = mb2w(resName);
return getimage(pResType_w.c_str(), pResName_w.c_str(), zoomWidth, zoomHeight);
}
int IMAGE::getimage(const wchar_t* resType, const wchar_t* resName, int zoomWidth, int zoomHeight)
{
(void)zoomWidth, (void)zoomHeight; // ignore
inittest(L"IMAGE::getimage");
struct _graph_setting* pg = &graph_setting;
HRSRC hrsrc = FindResourceW(pg->instance, resName, resType);
return getimage_from_resource(this, hrsrc);
}
int IMAGE::getimage(void* pMem, long size)
{
inittest(L"IMAGE::getimage");
if (pMem) {
DWORD dwSize = size;
HGLOBAL hGlobal = GlobalAlloc(GMEM_MOVEABLE, dwSize);
LPVOID pvData;
IStream* pStm;
if (hGlobal == NULL || (pvData = GlobalLock(hGlobal)) == NULL) {
return grAllocError;
}
memcpy(pvData, pMem, dwSize);
GlobalUnlock(hGlobal);
if (S_OK != dll::CreateStreamOnHGlobal(hGlobal, TRUE, &pStm)) {
return grNullPointer;
}
Gdiplus::Bitmap bitmap(pStm);
if (bitmap.GetLastStatus() != Gdiplus::Ok) {
return grError;
}
getimage_from_bitmap(this, bitmap);
// GlobalFree 不能在 Bitmap 读取完成之前调用
// 否则 Bitmap::LockBits() 返回 Win32Error 错误码
GlobalFree(hGlobal);
return grOk;
}
return grIOerror;
}
void IMAGE::putimage(PIMAGE imgDest, int xDest, int yDest, int widthDest, int heightDest, int xSrc, int ySrc, int srcWidth,
int srcHeight, DWORD dwRop) const
{
inittest(L"IMAGE::putimage");
const PCIMAGE img = CONVERT_IMAGE(imgDest);
if (img) {
SetStretchBltMode(img->m_hDC, COLORONCOLOR);
StretchBlt(img->m_hDC, xDest, yDest, widthDest, heightDest, m_hDC, xSrc, ySrc, srcWidth, srcHeight, dwRop);
}
CONVERT_IMAGE_END;
}
static void fix_rect_1size(PCIMAGE imgDest, PCIMAGE imgSrc, int* xDest, int* yDest,
int* xSrc, int* ySrc, int* width, int* height)
{
viewporttype vpt = imgDest->m_vpt;
Point srcPos(*xSrc, *ySrc);
Point dstPos(*xDest + vpt.left, *yDest + vpt.top);
/* 区域位于图像右下角,此区域内无内容 */
if ( (srcPos.x >= imgSrc->m_width) || (srcPos.y >= imgSrc->m_height)
|| (dstPos.x >= imgDest->m_width) || (dstPos.y >= imgDest->m_height))
{
*width = *height = 0;
return;
}
Bound srcBound;
srcBound.setTopLeft(*xSrc, *ySrc);
/* 调整区域: 宽高参数 <= 0 则将区域扩展至图像右下边缘,否则截断在 int 范围内*/
(*width <= 0) ? srcBound.setRight(imgSrc->m_width) : (void)srcBound.setLargeWidth(*width);
(*height <= 0) ? srcBound.setBottom(imgSrc->m_height) : (void)srcBound.setLargeHeight(*height);
/* 绘制区域 */
Bound dstBound;
dstBound.setTopLeft(dstPos);
dstBound.setLargeSize(srcBound.width(), srcBound.height());
/* 由视口区域计算绘制目标裁剪区域 */
Bound srcClip(0, 0, imgSrc->m_width, imgSrc->m_height);
Bound dstClip(0, 0, imgDest->m_width, imgDest->m_height);
dstClip.intersect(Bound(vpt.left, vpt.top, vpt.right, vpt.bottom));
srcBound.intersect(srcClip);
dstBound.intersect(dstClip);
Rect srcRect(srcBound);
Rect dstRect(dstBound);
/* 由共同区域求实际绘制区域 */
Point srcOffset(INT_MIN - srcPos.x, INT_MIN - srcPos.y);
Point dstOffset(INT_MIN - dstPos.x, INT_MIN - dstPos.y);
srcRect.offset(srcOffset.x, srcOffset.y);
dstRect.offset(dstOffset.x, dstOffset.y);
Rect actualRect = intersect(srcRect, dstRect);
if (actualRect.isValid()) {
*xDest = actualRect.x - dstOffset.x;
*yDest = actualRect.y - dstOffset.y;
*xSrc = actualRect.x - srcOffset.x;
*ySrc = actualRect.y - srcOffset.y;
*width = actualRect.width;
*height = actualRect.height;
} else {
*width = *height = 0;
}
}
int IMAGE::putimage_transparent(PIMAGE imgDest, // handle to dest
int xDest, // x-coord of destination upper-left corner
int yDest, // y-coord of destination upper-left corner
color_t transparentColor, // color to make transparent
int xSrc, // x-coord of source upper-left corner
int ySrc, // y-coord of source upper-left corner
int widthSrc, // width of source rectangle
int heightSrc // height of source rectangle
) const
{
inittest(L"IMAGE::putimage_transparent");
const PIMAGE img = CONVERT_IMAGE(imgDest);
if (img) {
PCIMAGE imgSrc = this;
int y, x;
DWORD ddx, dsx;
DWORD * pdp, *psp, cr;
// fix rect
fix_rect_1size(img, imgSrc, &xDest, &yDest, &xSrc, &ySrc, &widthSrc, &heightSrc);
if ((widthSrc == 0) || (heightSrc == 0))
return grOk;
// draw
pdp = img->m_pBuffer + yDest * img->m_width + xDest;
psp = imgSrc->m_pBuffer + ySrc * imgSrc->m_width + xSrc;
ddx = img->m_width - widthSrc;
dsx = imgSrc->m_width - widthSrc;
cr = transparentColor & 0x00FFFFFF;
for (y = 0; y < heightSrc; ++y) {
for (x = 0; x < widthSrc; ++x, ++psp, ++pdp) {
if ((*psp & 0x00FFFFFF) != cr) {
*pdp = EGECOLORA(*psp, EGEGET_A(*pdp));
}
}
pdp += ddx;
psp += dsx;
}
}
CONVERT_IMAGE_END;
return grOk;
}
int IMAGE::putimage_alphablend(PIMAGE imgDest, // handle to dest
int xDest, // x-coord of destination upper-left corner
int yDest, // y-coord of destination upper-left corner
unsigned char alpha, // alpha
int xSrc, // x-coord of source upper-left corner
int ySrc, // y-coord of source upper-left corner
int widthSrc, // width of source rectangle
int heightSrc,// height of source rectangle
alpha_type alphaType // alpha mode(straight alpha or premultiplied alpha)
) const
{
inittest(L"IMAGE::putimage_alphablend");
const PIMAGE img = CONVERT_IMAGE(imgDest);
if (img) {
if (alpha == 0)
return grOk;
PCIMAGE imgSrc = this;
fix_rect_1size(img, imgSrc, &xDest, &yDest, &xSrc, &ySrc, &widthSrc, &heightSrc);
if ((widthSrc == 0) || (heightSrc == 0))
return grOk;
if (alphaType == ALPHATYPE_PREMULTIPLIED) {
BLENDFUNCTION bf;
bf.BlendOp = AC_SRC_OVER;
bf.BlendFlags = 0;
bf.SourceConstantAlpha = alpha;
bf.AlphaFormat = AC_SRC_ALPHA;
// draw
dll::AlphaBlend(img->m_hDC, xDest, yDest, widthSrc, heightSrc,
imgSrc->m_hDC, xSrc, ySrc, widthSrc, heightSrc, bf);
} else {
DWORD* pdp = img->m_pBuffer + yDest * img->m_width + xDest;
DWORD* psp = imgSrc->m_pBuffer + ySrc * imgSrc->m_width + xSrc;
DWORD ddx = img->m_width - widthSrc;
DWORD dsx = imgSrc->m_width - widthSrc;
if (alpha == 0xFF) {
for (int y = 0; y < heightSrc; ++y) {
for (int x = 0; x < widthSrc; ++x, ++psp, ++pdp) {
DWORD d = *pdp, s = *psp;
*pdp = alphablend_inline(d, s);
}
pdp += ddx;
psp += dsx;
}
} else {
for (int y = 0; y < heightSrc; ++y) {
for (int x = 0; x < widthSrc; ++x, ++psp, ++pdp) {
DWORD d = *pdp, s = *psp;
*pdp = alphablend_inline(d, s, alpha);
}
pdp += ddx;
psp += dsx;
}
}
}