forked from iseahound/ImagePut
-
Notifications
You must be signed in to change notification settings - Fork 0
/
ImagePut.ahk
4309 lines (3495 loc) · 189 KB
/
ImagePut.ahk
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
; Script: ImagePut.ahk
; License: MIT License
; Author: Edison Hua (iseahound)
; Github: https://github.com/iseahound/ImagePut
; Date: 2023-03-02
; Version: 1.10
#Requires AutoHotkey v2.0-beta.13+
; Puts the image into a file format and returns a base64 encoded string.
; extension - File Encoding | string -> bmp, gif, jpg, png, tiff
; quality - JPEG Quality Level | integer -> 0 - 100
ImagePutBase64(image, extension := "", quality := "") {
return ImagePut("base64", image, extension, quality)
}
; Puts the image into a GDI+ Bitmap and returns a pointer.
ImagePutBitmap(image) {
return ImagePut("bitmap", image)
}
; Puts the image into a GDI+ Bitmap and returns a buffer object with GDI+ scope.
ImagePutBuffer(image) {
return ImagePut("buffer", image)
}
; Puts the image onto the clipboard and returns ClipboardAll().
ImagePutClipboard(image) {
return ImagePut("clipboard", image)
}
; Puts the image as the cursor and returns the variable A_Cursor.
; xHotspot - X Click Point | pixel -> 0 - width
; yHotspot - Y Click Point | pixel -> 0 - height
ImagePutCursor(image, xHotspot := "", yHotspot := "") {
return ImagePut("cursor", image, xHotspot, yHotspot)
}
; Puts the image onto a device context and returns the handle.
; alpha - Alpha Replacement Color | RGB -> 0xFFFFFF
ImagePutDC(image, alpha := "") {
return ImagePut("dc", image, alpha)
}
; Puts the image behind the desktop icons and returns the string "desktop".
ImagePutDesktop(image) {
return ImagePut("desktop", image)
}
; Puts the image into the most recently active explorer window.
ImagePutExplorer(image, default := "") {
return ImagePut("explorer", image, default)
}
; Puts the image into a file and returns its filepath.
; filepath - Filepath + Extension | string -> *.bmp, *.gif, *.jpg, *.png, *.tiff
; quality - JPEG Quality Level | integer -> 0 - 100
ImagePutFile(image, filepath := "", quality := "") {
return ImagePut("file", image, filepath, quality)
}
; Puts the image into a multipart/form-data in binary and returns a SafeArray COM Object.
; boundary - Content-Type | string -> multipart/form-data; boundary=something
ImagePutFormData(image, boundary := "ImagePut-abcdef") {
return ImagePut("formdata", image, boundary)
}
; Puts the image into a device independent bitmap and returns the handle.
; alpha - Alpha Replacement Color | RGB -> 0xFFFFFF
ImagePutHBitmap(image, alpha := "") {
return ImagePut("hBitmap", image, alpha)
}
; Puts the image into a file format and returns a hexadecimal encoded string.
; extension - File Encoding | string -> bmp, gif, jpg, png, tiff
; quality - JPEG Quality Level | integer -> 0 - 100
ImagePutHex(image, extension := "", quality := "") {
return ImagePut("hex", image, extension, quality)
}
; Puts the image into an icon and returns the handle.
ImagePutHIcon(image) {
return ImagePut("hIcon", image)
}
; Puts the image into a file format and returns a pointer to a RandomAccessStream.
; extension - File Encoding | string -> bmp, gif, jpg, png, tiff
; quality - JPEG Quality Level | integer -> 0 - 100
ImagePutRandomAccessStream(image, extension := "", quality := "") {
return ImagePut("RandomAccessStream", image, extension, quality)
}
; Puts the image into a file format and returns a SafeArray COM Object.
; extension - File Encoding | string -> bmp, gif, jpg, png, tiff
; quality - JPEG Quality Level | integer -> 0 - 100
ImagePutSafeArray(image, extension := "", quality := "") {
return ImagePut("safeArray", image, extension, quality)
}
; Puts the image on the shared screen device context and returns an array of coordinates.
; screenshot - Screen Coordinates | array -> [x,y,w,h] or [0,0]
; alpha - Alpha Replacement Color | RGB -> 0xFFFFFF
ImagePutScreenshot(image, screenshot := "", alpha := "") {
return ImagePut("screenshot", image, screenshot, alpha)
}
; Puts the image into a file mapping and returns a buffer object sharable across processes.
; name - Global Name | string -> "Alice"
ImagePutSharedBuffer(image, name := "") {
return ImagePut("SharedBuffer", image, name)
}
; Puts the image into a file format and returns a pointer to a stream.
; extension - File Encoding | string -> bmp, gif, jpg, png, tiff
; quality - JPEG Quality Level | integer -> 0 - 100
ImagePutStream(image, extension := "", quality := "") {
return ImagePut("stream", image, extension, quality)
}
; Puts the image into a file format and returns a URI string.
; extension - File Encoding | string -> bmp, gif, jpg, png, tiff
; quality - JPEG Quality Level | integer -> 0 - 100
ImagePutURI(image, extension := "", quality := "") {
return ImagePut("uri", image, extension, quality)
}
; Puts the image as the desktop wallpaper and returns the string "wallpaper".
ImagePutWallpaper(image) {
return ImagePut("wallpaper", image)
}
; Puts the image into a WICBitmap and returns the pointer to the interface.
ImagePutWICBitmap(image) {
return ImagePut("wicBitmap", image)
}
; Puts the image in a window and returns a handle to a window.
; title - Window Title | string -> MyTitle
; pos - Window Coordinates | array -> [x,y,w,h] or [0,0]
; style - Window Style | uint -> WS_VISIBLE
; styleEx - Window Extended Style | uint -> WS_EX_LAYERED
; parent - Window Parent | ptr -> hwnd
ImagePutWindow(image, title := "", pos := "", style := 0x82C80000, styleEx := 0x9, parent := "") {
return ImagePut("window", image, title, pos, style, styleEx, parent)
}
; title - Window Title | string -> MyTitle
; pos - Window Coordinates | array -> [x,y,w,h] or [0,0]
; style - Window Style | uint -> WS_VISIBLE
; styleEx - Window Extended Style | uint -> WS_EX_LAYERED
; parent - Window Parent | ptr -> hwnd
ImageShow(image, title := "", pos := "", style := 0x90000000, styleEx := 0x80088, parent := "") {
return ImagePut("show", image, title, pos, style, styleEx, parent)
}
ImageDestroy(image) {
return ImagePut.Destroy(image)
}
ImageWidth(image) {
return ImagePut.Dimensions(image)[1]
}
ImageHeight(image) {
return ImagePut.Dimensions(image)[2]
}
/*
ImagePut(cotype, image, p*) {
return ImagePut.call(cotype, image, p*)
}
ImageEqual(images*) {
return ImageEqual.call(images*)
}
*/
class ImagePut {
static decode := False ; Forces conversion using a bitmap. The original file encoding will be lost.
static validate := False ; Always copies image data into memory instead of passing references.
static call(cotype, image, p*) {
; Start!
this.gdiplusStartup()
; Take a guess as to what the image might be. (>95% accuracy!)
try type := this.DontVerifyImageType(&image, &keywords)
catch
type := this.ImageType(image)
crop := keywords.crop
scale := keywords.scale, upscale := keywords.upscale, downscale := keywords.downscale
decode := (keywords.decode != "") ? keywords.decode : this.decode
validate := (keywords.validate != "") ? keywords.validate : this.validate
; #1 - Stream intermediate.
if not decode and not crop and not (scale || upscale || downscale)
and (type ~= "^(?i:clipboard_png|pdf|url|file|stream|RandomAccessStream|hex|base64)$")
and (cotype ~= "^(?i:file|stream|RandomAccessStream|hex|base64|uri|explorer|safeArray|formData)$")
and (!p.Has(1) || p[1] == "") { ; For now, disallow any specification of extensions.
; Convert via stream intermediate.
if !(pStream := this.ToStream(type, image, keywords))
throw Error("pStream cannot be zero.")
coimage := this.StreamToCoimage(cotype, pStream, p*)
; Prevents the stream object from being freed.
if (cotype = "stream")
ObjAddRef(pStream)
; Free the temporary stream object.
ObjRelease(pStream)
}
; #2 - Fallback to GDI+ bitmap as the intermediate.
else {
; GdipImageForceValidation must be called immediately or it fails without any errors.
; It load the image pixels to the bitmap buffer, increasing memory usage and prevents
; changes to the pixels while bypassing any copy-on-write and copy on LockBits(read) behavior.
; Convert via GDI+ bitmap intermediate.
if !(pBitmap := this.ToBitmap(type, image, keywords))
throw Error("pBitmap cannot be zero.")
(validate) && DllCall("gdiplus\GdipImageForceValidation", "ptr", pBitmap)
(crop) && this.BitmapCrop(&pBitmap, crop)
(scale) && this.BitmapScale(&pBitmap, scale)
(upscale) && this.BitmapScale(&pBitmap, upscale, 1)
(downscale) && this.BitmapScale(&pBitmap, downscale, -1)
coimage := this.BitmapToCoimage(cotype, pBitmap, p*)
; Clean up the pBitmap copy. Export raw pointers if requested.
if !(cotype = "bitmap")
DllCall("gdiplus\GdipDisposeImage", "ptr", pBitmap)
}
; Check for dangling pointers.
this.gdiplusShutdown(cotype)
return coimage
}
static get(self, name) {
return ObjHasOwnProp(self, name) ? self.%name% : ""
}
static inputs := [
"clipboard_png",
"clipboard",
"object",
"buffer",
"screenshot",
"window",
"desktop",
"wallpaper",
"cursor",
"pdf",
"url",
"file",
"hex",
"base64",
"monitor",
"dc",
"hBitmap",
"hIcon",
"bitmap",
"stream",
"RandomAccessStream",
"wicBitmap",
"d2dBitmap",
"sprite"
]
static DontVerifyImageType(&image, &keywords := "") {
; Sentinel value: Returns the empty string for unknown properties.
keywords := {base: {__get: (self, name, *) => this.get(self, name)}}
; Try ImageType.
if !IsObject(image)
throw Error("Must be an object.")
; Goto ImageType.
if ObjHasOwnProp(image, "image") {
keywords := image
keywords.base := {__get: (self, name, *) => this.get(self, name)}
image := image.image
throw Error("Must catch this error with ImageType.")
}
; Skip ImageType.
for type in this.inputs
if ObjHasOwnProp(image, type) {
keywords := image
keywords.base := {__get: (self, name, *) => this.get(self, name)}
image := image.%type%
return type
}
; Continue ImageType.
throw Error("Invalid type.")
}
static ImageType(image) {
; Throw if the image is an empty string.
if (image == "")
throw Error("Image data is an empty string.")
if IsObject(image) {
if (image.HasOwnProp("prototype") && image.prototype.HasOwnProp("__class") && image.prototype.__class == "ClipboardAll"
|| image.base.HasOwnProp("__class") && image.base.__class == "ClipboardAll") {
; A "clipboard_png" is a pointer to a PNG stream saved as the "png" clipboard format.
if DllCall("IsClipboardFormatAvailable", "uint", DllCall("RegisterClipboardFormat", "str", "png", "uint"))
return "clipboard_png"
; A "clipboard" is a handle to a GDI bitmap saved as CF_BITMAP.
if DllCall("IsClipboardFormatAvailable", "uint", 2)
return "clipboard"
throw Error("Clipboard format not supported.")
}
; A "object" has a pBitmap property that points to an internal GDI+ bitmap.
if image.HasOwnProp("pBitmap")
return "object"
; A "buffer" is an object with ptr and size properties.
if image.HasOwnProp("ptr") && image.HasOwnProp("size")
return "buffer"
; A "window" is an object with an hwnd property.
if image.HasOwnProp("hwnd")
return "window"
; A "screenshot" is an array of 4 numbers.
if (image[1] ~= "^-?\d+$" && image[2] ~= "^-?\d+$" && image[3] ~= "^-?\d+$" && image[4] ~= "^-?\d+$")
return "screenshot"
throw Error("Image type could not be identified.")
}
; A non-zero "monitor" number identifies each display uniquely; and 0 refers to the entire virtual screen.
if (image ~= "^\d+$" && image >= 0 && image <= MonitorGetCount())
return "monitor"
; A "desktop" is a hidden window behind the desktop icons created by ImagePutDesktop.
if (image = "desktop")
return "desktop"
; A "wallpaper" is the desktop wallpaper.
if (image = "wallpaper")
return "wallpaper"
; A "cursor" is the name of a known cursor name.
if (image ~= "(?i)^A_Cursor|Unknown|(IDC_)?(AppStarting|Arrow|Cross|Hand(writing)?|"
. "Help|IBeam|No|Pin|Person|SizeAll|SizeNESW|SizeNS|SizeNWSE|SizeWE|UpArrow|Wait)$")
return "cursor"
; A "pdf" is either a file or url with a .pdf extension.
if (image ~= "\.pdf$") && (FileExist(image) || this.is_url(image))
return "pdf"
; A "url" satisfies the url format.
if this.is_url(image)
return "url"
; A "file" is stored on the disk or network.
if FileExist(image)
return "file"
; A "window" is anything considered a Window Title including ahk_class and "A".
if WinExist(image)
return "window"
; A "hex" string is binary image data encoded into text using hexadecimal.
if (StrLen(image) >= 48) && (image ~= "^\s*(?:[A-Fa-f0-9]{2})*+\s*$")
return "hex"
; A "base64" string is binary image data encoded into text using standard 64 characters.
if (StrLen(image) >= 32) && (image ~= "^\s*(?:data:image\/[a-z]+;base64,)?"
. "(?:[A-Za-z0-9+\/]{4})*+(?:[A-Za-z0-9+\/]{3}=|[A-Za-z0-9+\/]{2}==)?\s*$")
return "base64"
if (image ~= "^-?\d+$") {
; A "dc" is a handle to a GDI device context.
if (DllCall("GetObjectType", "ptr", image, "uint") == 3 || DllCall("GetObjectType", "ptr", image, "uint") == 10)
return "dc"
; An "hBitmap" is a handle to a GDI Bitmap.
if (DllCall("GetObjectType", "ptr", image, "uint") == 7)
return "hBitmap"
; An "hIcon" is a handle to a GDI icon.
if DllCall("DestroyIcon", "ptr", DllCall("CopyIcon", "ptr", image, "ptr"))
return "hIcon"
; A "bitmap" is a pointer to a GDI+ Bitmap.
try if !DllCall("gdiplus\GdipGetImageType", "ptr", image, "ptr*", &type:=0) && (type == 1)
return "bitmap"
; Note 1: All GDI+ functions add 1 to the reference count of COM objects.
; Note 2: GDI+ pBitmaps that are queried cease to stay pBitmaps.
; Note 3: Critical error for ranges 0-4095 on v1 and 0-65535 on v2.
ObjRelease(image) ; Therefore do not move this, it has been tested.
; A "stream" is a pointer to the IStream interface.
try if ComObjQuery(image, "{0000000C-0000-0000-C000-000000000046}")
return "stream"
; A "RandomAccessStream" is a pointer to the IRandomAccessStream interface.
try if ComObjQuery(image, "{905A0FE1-BC53-11DF-8C49-001E4FC686DA}")
return "RandomAccessStream"
; A "wicBitmap" is a pointer to a IWICBitmapSource.
try if ComObjQuery(image, "{00000120-A8F2-4877-BA0A-FD2B6645FB94}")
return "wicBitmap"
; A "d2dBitmap" is a pointer to a ID2D1Bitmap.
try if ComObjQuery(image, "{A2296057-EA42-4099-983B-539FB6505426}")
return "d2dBitmap"
}
; For more helpful error messages: Catch file names without extensions!
for extension in ["bmp","dib","rle","jpg","jpeg","jpe","jfif","gif","tif","tiff","png","ico","exe","dll"]
if FileExist(image "." extension)
throw Error("A ." extension " file extension is required!", -3)
throw Error("Image type could not be identified.")
}
static ToBitmap(type, image, k := "") {
; Sentinel value: Returns the empty string for unknown properties.
(!k) && k := {__get: (self, name, *) => this.get(self, name)}
if (type = "clipboard_png")
return this.from_clipboard_png()
if (type = "clipboard")
return this.from_clipboard()
if (type = "object")
return this.from_object(image)
if (type = "buffer")
return this.from_buffer(image)
if (type = "screenshot")
return this.from_screenshot(image)
if (type = "window")
return this.from_window(image)
if (type = "desktop")
return this.from_desktop()
if (type = "wallpaper")
return this.from_wallpaper()
if (type = "cursor")
return this.from_cursor()
if (type = "pdf")
return this.from_pdf(image, k.index)
if (type = "url")
return this.from_url(image)
if (type = "file")
return this.from_file(image)
if (type = "hex")
return this.from_hex(image)
if (type = "base64")
return this.from_base64(image)
if (type = "monitor")
return this.from_monitor(image)
if (type = "dc")
return this.from_dc(image)
if (type = "hBitmap")
return this.from_hBitmap(image)
if (type = "hIcon")
return this.from_hIcon(image)
if (type = "bitmap")
return this.from_bitmap(image)
if (type = "stream")
return this.from_stream(image)
if (type = "RandomAccessStream")
return this.from_RandomAccessStream(image)
if (type = "wicBitmap")
return this.from_wicBitmap(image)
if (type = "sprite")
return this.from_sprite(image)
throw Error("Conversion from " type " to bitmap is not supported.")
}
static BitmapToCoimage(cotype, pBitmap, p1:="", p2:="", p3:="", p4:="", p5:="", p*) {
; BitmapToCoimage("clipboard", pBitmap)
if (cotype = "clipboard" || cotype = "clipboard_png")
return this.to_clipboard(pBitmap)
; BitmapToCoimage("buffer", pBitmap)
if (cotype = "buffer")
return this.to_buffer(pBitmap)
; BitmapToCoimage("sharedbuffer", pBitmap, p1)
if (cotype = "sharedbuffer")
return this.to_sharedbuffer(pBitmap, p1)
; BitmapToCoimage("screenshot", pBitmap, screenshot, alpha)
if (cotype = "screenshot")
return this.to_screenshot(pBitmap, p1, p2)
; BitmapToCoimage("show", pBitmap, title, pos, style, styleEx, parent)
if (cotype = "show")
return this.show(pBitmap, p1, p2, p3, p4, p5)
; BitmapToCoimage("window", pBitmap, title, pos, style, styleEx, parent)
if (cotype = "window")
return this.to_window(pBitmap, p1, p2, p3, p4, p5)
; BitmapToCoimage("desktop", pBitmap)
if (cotype = "desktop")
return this.to_desktop(pBitmap)
; BitmapToCoimage("wallpaper", pBitmap)
if (cotype = "wallpaper")
return this.to_wallpaper(pBitmap)
; BitmapToCoimage("cursor", pBitmap, xHotspot, yHotspot)
if (cotype = "cursor")
return this.to_cursor(pBitmap, p1, p2)
; BitmapToCoimage("url", pBitmap)
if (cotype = "url")
return this.to_url(pBitmap)
; BitmapToCoimage("file", pBitmap, filepath, quality)
if (cotype = "file")
return this.to_file(pBitmap, p1, p2)
; BitmapToCoimage("hex", pBitmap, extension, quality)
if (cotype = "hex")
return this.to_hex(pBitmap, p1, p2)
; BitmapToCoimage("base64", pBitmap, extension, quality)
if (cotype = "base64")
return this.to_base64(pBitmap, p1, p2)
; BitmapToCoimage("uri", pBitmap, extension, quality)
if (cotype = "uri")
return this.to_uri(pBitmap, p1, p2)
; BitmapToCoimage("dc", pBitmap, alpha)
if (cotype = "dc")
return this.to_dc(pBitmap, p1)
; BitmapToCoimage("hBitmap", pBitmap, alpha)
if (cotype = "hBitmap")
return this.to_hBitmap(pBitmap, p1)
; BitmapToCoimage("hIcon", pBitmap)
if (cotype = "hIcon")
return this.to_hIcon(pBitmap)
; BitmapToCoimage("bitmap", pBitmap)
if (cotype = "bitmap")
return pBitmap
; BitmapToCoimage("stream", pBitmap, extension, quality)
if (cotype = "stream")
return this.to_stream(pBitmap, p1, p2)
; BitmapToCoimage("RandomAccessStream", pBitmap, extension, quality)
if (cotype = "RandomAccessStream")
return this.to_RandomAccessStream(pBitmap, p1, p2)
; BitmapToCoimage("wicBitmap", pBitmap)
if (cotype = "wicBitmap")
return this.to_wicBitmap(pBitmap)
; BitmapToCoimage("explorer", pBitmap, default)
if (cotype = "explorer")
return this.to_explorer(pBitmap, p1)
; BitmapToCoimage("safeArray", pBitmap, extension, quality)
if (cotype = "safeArray")
return this.to_safeArray(pBitmap, p1, p2)
; BitmapToCoimage("formData", pBitmap, boundary, extension, quality)
if (cotype = "formData")
return this.to_formData(pBitmap, p1, p2, p3)
throw Error("Conversion from bitmap to " cotype " is not supported.")
}
static ToStream(type, image, k := "") {
; Sentinel value: Returns the empty string for unknown properties.
(!k) && k := {__get: (self, name, *) => this.get(self, name)}
if (type = "clipboard_png")
return this.get_clipboard_png()
if (type = "pdf")
return this.get_pdf(image, k.index)
if (type = "url")
return this.get_url(image)
if (type = "file")
return this.get_file(image)
if (type = "hex")
return this.get_hex(image)
if (type = "base64")
return this.get_base64(image)
if (type = "stream")
return this.get_stream(image)
if (type = "RandomAccessStream")
return this.get_RandomAccessStream(image)
throw Error("Conversion from " type " to stream is not supported.")
}
static StreamToCoimage(cotype, pStream, p1 := "", p2 := "", p*) {
; StreamToCoimage("file", pStream, filepath)
if (cotype = "file")
return this.set_file(pStream, p1)
; StreamToCoimage("hex", pStream)
if (cotype = "hex")
return this.set_hex(pStream)
; StreamToCoimage("base64", pStream)
if (cotype = "base64")
return this.set_base64(pStream)
; StreamToCoimage("uri", pStream)
if (cotype = "uri")
return this.set_uri(pStream)
; StreamToCoimage("stream", pStream)
if (cotype = "stream")
return pStream
; StreamToCoimage("RandomAccessStream", pStream)
if (cotype = "RandomAccessStream")
return this.set_RandomAccessStream(pStream)
; StreamToCoimage("explorer", pStream, default)
if (cotype = "explorer")
return this.set_explorer(pStream, p1)
; StreamToCoimage("safeArray", pStream)
if (cotype = "safeArray")
return this.set_safeArray(pStream)
; StreamToCoimage("formData", pStream, boundary)
if (cotype = "formData")
return this.set_formData(pStream, p1)
throw Error("Conversion from stream to " cotype " is not supported.")
}
static BitmapCrop(&pBitmap, crop) {
if not (IsObject(crop)
&& crop[1] ~= "^-?\d+(\.\d*)?%?$" && crop[2] ~= "^-?\d+(\.\d*)?%?$"
&& crop[3] ~= "^-?\d+(\.\d*)?%?$" && crop[4] ~= "^-?\d+(\.\d*)?%?$")
throw Error("Invalid crop.")
; Get Bitmap width, height, and format.
DllCall("gdiplus\GdipGetImageWidth", "ptr", pBitmap, "uint*", &width:=0)
DllCall("gdiplus\GdipGetImageHeight", "ptr", pBitmap, "uint*", &height:=0)
DllCall("gdiplus\GdipGetImagePixelFormat", "ptr", pBitmap, "int*", &format:=0)
; Abstraction Shift.
; Previously, real values depended on abstract values.
; Now, real values have been resolved, and abstract values depend on reals.
; Are the numbers percentages?
(crop[1] ~= "%$") && crop[1] := SubStr(crop[1], 1, -1) * 0.01 * width
(crop[2] ~= "%$") && crop[2] := SubStr(crop[2], 1, -1) * 0.01 * height
(crop[3] ~= "%$") && crop[3] := SubStr(crop[3], 1, -1) * 0.01 * width
(crop[4] ~= "%$") && crop[4] := SubStr(crop[4], 1, -1) * 0.01 * height
; If numbers are negative, subtract the values from the edge.
crop[1] := Abs(crop[1])
crop[2] := Abs(crop[2])
crop[3] := (crop[3] < 0) ? width - Abs(crop[3]) - Abs(crop[1]) : crop[3]
crop[4] := (crop[4] < 0) ? height - Abs(crop[4]) - Abs(crop[2]) : crop[4]
; Round to the nearest integer. Reminder: width and height are distances, not coordinates.
crop[1] := Round(crop[1])
crop[2] := Round(crop[2])
crop[3] := Round(crop[1] + crop[3]) - Round(crop[1])
crop[4] := Round(crop[2] + crop[4]) - Round(crop[2])
; Avoid cropping if no changes are detected.
if (crop[1] = 0 && crop[2] = 0 && crop[3] == width && crop[4] == height)
return pBitmap
; Minimum size is 1 x 1. Ensure that coordinates can never exceed the expected Bitmap area.
safe_x := (crop[1] >= width)
safe_y := (crop[2] >= height)
safe_w := (crop[3] <= 0 || crop[1] + crop[3] > width)
safe_h := (crop[4] <= 0 || crop[2] + crop[4] > height)
; Abort cropping if any of the changes would exceed a safe bound.
if (safe_x || safe_y || safe_w || safe_h)
return pBitmap
; Clone
DllCall("gdiplus\GdipCloneBitmapAreaI"
, "int", crop[1]
, "int", crop[2]
, "int", crop[3]
, "int", crop[4]
, "int", format
, "ptr", pBitmap
, "ptr*", &pBitmapCrop:=0)
DllCall("gdiplus\GdipDisposeImage", "ptr", pBitmap)
return pBitmap := pBitmapCrop
}
static BitmapScale(&pBitmap, scale, direction := 0) {
if not (IsObject(scale) && ((scale[1] ~= "^\d+$") || (scale[2] ~= "^\d+$")) || (scale ~= "^\d+(\.\d+)?$"))
throw Error("Invalid scale.")
; Get Bitmap width, height, and format.
DllCall("gdiplus\GdipGetImageWidth", "ptr", pBitmap, "uint*", &width:=0)
DllCall("gdiplus\GdipGetImageHeight", "ptr", pBitmap, "uint*", &height:=0)
DllCall("gdiplus\GdipGetImagePixelFormat", "ptr", pBitmap, "int*", &format:=0)
if IsObject(scale) {
safe_w := (scale[1] ~= "^\d+$") ? scale[1] : Round(width / height * scale[2])
safe_h := (scale[2] ~= "^\d+$") ? scale[2] : Round(height / width * scale[1])
} else {
safe_w := Ceil(width * scale)
safe_h := Ceil(height * scale)
}
; Avoid drawing if no changes detected.
if (safe_w = width && safe_h = height)
return pBitmap
; Force upscaling.
if (direction > 0 and (safe_w < width && safe_h < height))
return pBitmap
; Force downscaling.
if (direction < 0 and (safe_w > width && safe_h > height))
return pBitmap
; Create a new bitmap and get the graphics context.
DllCall("gdiplus\GdipCreateBitmapFromScan0"
, "int", safe_w, "int", safe_h, "int", 0, "int", format, "ptr", 0, "ptr*", &pBitmapScale:=0)
DllCall("gdiplus\GdipGetImageGraphicsContext", "ptr", pBitmapScale, "ptr*", &pGraphics:=0)
; Set settings in graphics context.
DllCall("gdiplus\GdipSetPixelOffsetMode", "ptr", pGraphics, "int", 2) ; Half pixel offset.
DllCall("gdiplus\GdipSetCompositingMode", "ptr", pGraphics, "int", 1) ; Overwrite/SourceCopy.
DllCall("gdiplus\GdipSetInterpolationMode", "ptr", pGraphics, "int", 7) ; HighQualityBicubic
; Draw Image.
DllCall("gdiplus\GdipCreateImageAttributes", "ptr*", &ImageAttr:=0)
DllCall("gdiplus\GdipSetImageAttributesWrapMode", "ptr", ImageAttr, "int", 3) ; WrapModeTileFlipXY
DllCall("gdiplus\GdipDrawImageRectRectI"
, "ptr", pGraphics
, "ptr", pBitmap
, "int", 0, "int", 0, "int", safe_w, "int", safe_h ; destination rectangle
, "int", 0, "int", 0, "int", width, "int", height ; source rectangle
, "int", 2
, "ptr", ImageAttr
, "ptr", 0
, "ptr", 0)
DllCall("gdiplus\GdipDisposeImageAttributes", "ptr", ImageAttr)
; Clean up the graphics context.
DllCall("gdiplus\GdipDeleteGraphics", "ptr", pGraphics)
DllCall("gdiplus\GdipDisposeImage", "ptr", pBitmap)
return pBitmap := pBitmapScale
}
static is_url(url) {
; Thanks dperini - https://gist.github.com/dperini/729294
; Also see for comparisons: https://mathiasbynens.be/demo/url-regex
; Modified to be compatible with AutoHotkey. \u0000 -> \x{0000}.
; Force the declaration of the protocol because WinHttp requires it.
return url ~= "^(?i)"
. "(?:(?:https?|ftp):\/\/)" ; protocol identifier (FORCE)
. "(?:\S+(?::\S*)?@)?" ; user:pass BasicAuth (optional)
. "(?:"
; IP address exclusion
; private & local networks
. "(?!(?:10|127)(?:\.\d{1,3}){3})"
. "(?!(?:169\.254|192\.168)(?:\.\d{1,3}){2})"
. "(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})"
; IP address dotted notation octets
; excludes loopback network 0.0.0.0
; excludes reserved space >= 224.0.0.0
; excludes network & broadcast addresses
; (first & last IP address of each class)
. "(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])"
. "(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}"
. "(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))"
. "|"
; host & domain names, may end with dot
; can be replaced by a shortest alternative
; (?![-_])(?:[-\\w\\u00a1-\\uffff]{0,63}[^-_]\\.)+
. "(?:(?:[a-z0-9\x{00a1}-\x{ffff}][a-z0-9\x{00a1}-\x{ffff}_-]{0,62})?[a-z0-9\x{00a1}-\x{ffff}]\.)+"
; TLD identifier name, may end with dot
. "(?:[a-z\x{00a1}-\x{ffff}]{2,}\.?)"
. ")"
. "(?::\d{2,5})?" ; port number (optional)
. "(?:[/?#]\S*)?$" ; resource path (optional)
}
static from_clipboard() {
; Open the clipboard with exponential backoff.
loop
if DllCall("OpenClipboard", "ptr", A_ScriptHwnd)
break
else
if A_Index < 6
Sleep (2**(A_Index-1) * 30)
else throw Error("Clipboard could not be opened.")
; Fallback to CF_BITMAP. This format does not support transparency even with to_hBitmap().
if !DllCall("IsClipboardFormatAvailable", "uint", 2)
throw Error("Clipboard does not have CF_BITMAP data.")
if !(hbm := DllCall("GetClipboardData", "uint", 2, "ptr"))
throw Error("Shared clipboard data has been deleted.")
DllCall("gdiplus\GdipCreateBitmapFromHBITMAP", "ptr", hbm, "ptr", 0, "ptr*", &pBitmap:=0)
DllCall("DeleteObject", "ptr", hbm)
DllCall("CloseClipboard")
return pBitmap
}
static from_clipboard_png() {
pStream := this.get_clipboard_png()
DllCall("gdiplus\GdipCreateBitmapFromStream", "ptr", pStream, "ptr*", &pBitmap:=0)
ObjRelease(pStream)
return pBitmap
}
static get_clipboard_png() {
; Open the clipboard with exponential backoff.
loop
if DllCall("OpenClipboard", "ptr", A_ScriptHwnd)
break
else
if A_Index < 6
Sleep (2**(A_Index-1) * 30)
else throw Error("Clipboard could not be opened.")
png := DllCall("RegisterClipboardFormat", "str", "png", "uint")
if !DllCall("IsClipboardFormatAvailable", "uint", png)
throw Error("Clipboard does not have PNG stream data.")
if !(hData := DllCall("GetClipboardData", "uint", png, "ptr"))
throw Error("Shared clipboard data has been deleted.")
; Allow the stream to be freed while leaving the hData intact.
; Please read: https://devblogs.microsoft.com/oldnewthing/20210930-00/?p=105745
DllCall("ole32\CreateStreamOnHGlobal", "ptr", hData, "int", False, "ptr*", &pStream:=0, "hresult")
DllCall("CloseClipboard")
return pStream
}
static from_object(image) {
return this.from_bitmap(image.pBitmap)
}
static from_buffer(image) {
; to do
}
static read_screen() {
assert(statement, message) {
if !statement
throw ValueError(message, -1, statement)
}
; Load DirectX
assert IDXGIFactory := CreateDXGIFactory(), "Create IDXGIFactory failed."
CreateDXGIFactory() {
if !DllCall("GetModuleHandle", "str", "DXGI")
DllCall("LoadLibrary", "str", "DXGI")
if !DllCall("GetModuleHandle", "str", "D3D11")
DllCall("LoadLibrary", "str", "D3D11")
DllCall("ole32\CLSIDFromString", "wstr", "{7b7166ec-21c7-44ae-b21a-c9ae321ae369}", "ptr", riid := Buffer(16, 0), "hresult")
DllCall("DXGI\CreateDXGIFactory1", "ptr", riid, "ptr*", &ppFactory:=0, "hresult")
return ppFactory
}
; Get monitor?
loop {
ComCall(IDXGIFactory_EnumAdapters := 7, IDXGIFactory, "uint", A_Index-1, "ptr*", &IDXGIAdapter:=0)
loop {
try ComCall(IDXGIAdapter_EnumOutputs := 7, IDXGIAdapter, "uint", A_Index-1, "ptr*", &IDXGIOutput:=0)
catch OSError as e
if e.number = 0x887A0002 ; DXGI_ERROR_NOT_FOUND
break
else throw
ComCall(IDXGIOutput_GetDesc := 7, IDXGIOutput, "ptr", DXGI_OUTPUT_DESC := Buffer(88+A_PtrSize, 0))
Width := NumGet(DXGI_OUTPUT_DESC, 72, "int")
Height := NumGet(DXGI_OUTPUT_DESC, 76, "int")
AttachedToDesktop := NumGet(DXGI_OUTPUT_DESC, 80, "int")
if (AttachedToDesktop = 1)
break 2
}
}
; Ensure the desktop is connected.
assert AttachedToDesktop, "No adapter attached to desktop."
; Load direct3d
DllCall("D3D11\D3D11CreateDevice"
, "ptr", IDXGIAdapter ; pAdapter
, "int", D3D_DRIVER_TYPE_UNKNOWN := 0 ; DriverType
, "ptr", 0 ; Software
, "uint", 0 ; Flags
, "ptr", 0 ; pFeatureLevels
, "uint", 0 ; FeatureLevels
, "uint", D3D11_SDK_VERSION := 7 ; SDKVersion
, "ptr*", &d3d_device:=0 ; ppDevice
, "ptr*", 0 ; pFeatureLevel
, "ptr*", &d3d_context:=0 ; ppImmediateContext
,"hresult")
; Retrieve the desktop duplication API
IDXGIOutput1 := ComObjQuery(IDXGIOutput, "{00cddea8-939b-4b83-a340-a685226666cc}")
ComCall(IDXGIOutput1_DuplicateOutput := 22, IDXGIOutput1, "ptr", d3d_device, "ptr*", &Duplication:=0)
ComCall(IDXGIOutputDuplication_GetDesc := 7, Duplication, "ptr", DXGI_OUTDUPL_DESC := Buffer(36, 0))
DesktopImageInSystemMemory := NumGet(DXGI_OUTDUPL_DESC, 32, "uint")
Sleep 50 ; As I understand - need some sleep for successful connecting to IDXGIOutputDuplication interface
; Create the texture onto which the desktop will be copied to.
D3D11_TEXTURE2D_DESC := Buffer(44, 0)
NumPut("uint", width, D3D11_TEXTURE2D_DESC, 0) ; Width
NumPut("uint", height, D3D11_TEXTURE2D_DESC, 4) ; Height
NumPut("uint", 1, D3D11_TEXTURE2D_DESC, 8) ; MipLevels
NumPut("uint", 1, D3D11_TEXTURE2D_DESC, 12) ; ArraySize
NumPut("uint", DXGI_FORMAT_B8G8R8A8_UNORM := 87, D3D11_TEXTURE2D_DESC, 16) ; Format
NumPut("uint", 1, D3D11_TEXTURE2D_DESC, 20) ; SampleDescCount
NumPut("uint", 0, D3D11_TEXTURE2D_DESC, 24) ; SampleDescQuality
NumPut("uint", D3D11_USAGE_STAGING := 3, D3D11_TEXTURE2D_DESC, 28) ; Usage
NumPut("uint", 0, D3D11_TEXTURE2D_DESC, 32) ; BindFlags
NumPut("uint", D3D11_CPU_ACCESS_READ := 0x20000, D3D11_TEXTURE2D_DESC, 36) ; CPUAccessFlags
NumPut("uint", 0, D3D11_TEXTURE2D_DESC, 40) ; MiscFlags
ComCall(ID3D11Device_CreateTexture2D := 5, d3d_device, "ptr", D3D11_TEXTURE2D_DESC, "ptr", 0, "ptr*", &staging_tex:=0)
; Persist the concept of a desktop_resource as a closure???
local desktop_resource
Update(this, timeout := unset) {
; Unbind resources.
Unbind()
; Allocate a shared buffer for all calls of AcquireNextFrame.
static DXGI_OUTDUPL_FRAME_INFO := Buffer(48, 0)
if !IsSet(timeout) {
; The following loop structure repeatedly checks for a new frame.
loop {
; Ask if there is a new frame available immediately.
try ComCall(IDXGIOutputDuplication_AcquireNextFrame := 8, Duplication, "uint", 0, "ptr", DXGI_OUTDUPL_FRAME_INFO, "ptr*", &desktop_resource:=0)
catch OSError as e
if e.number = 0x887A0027 ; DXGI_ERROR_WAIT_TIMEOUT