-
Notifications
You must be signed in to change notification settings - Fork 28
/
ImagePut.ahk
5497 lines (4485 loc) · 257 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".
; See ImageShow for parameter descriptions.
ImagePutDesktop(image, title := "", pos := "", style := 0x50000000, styleEx := 0x80000, parent := "", playback := True, cache := False) {
return ImagePut("Desktop", image, title, pos, style, styleEx, parent, playback, cache)
}
; Puts the image as an encoded format into a binary data object.
; extension - File Encoding | string -> bmp, gif, jpg, png, tiff
; quality - JPEG Quality Level | integer -> 0 - 100
ImagePutEncodedBuffer(image, extension := "", quality := "") {
return ImagePut("EncodedBuffer", image, extension, quality)
}
; Puts the image into the currently active explorer window.
; default_dir - Default Directory | string -> C:\Users\Me\Pictures
; inactive - Inactive Explorer Wnds? | bool -> False
ImagePutExplorer(image, default_dir := "", inactive := False) {
return ImagePut("Explorer", image, default_dir, inactive)
}
; 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 abc 321 xyz--") {
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 -> "SharedBuffer"
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 base64 string and returns a Uniform Resource Identifier.
; 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)
}
; Uploads the image onto Imgur and returns the URL hyperlink.
; extension - File Encoding | string -> bmp, gif, jpg, png, tiff
; quality - JPEG Quality Level | integer -> 0 - 100
ImagePutURL(image, extension := "", quality := "") {
return ImagePut("URL", 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 (with a border) and returns a handle to a window.
; See ImageShow for parameter descriptions.
ImagePutWindow(image, title := "", pos := "", style := 0x82C80000, styleEx := 0x9, parent := "", playback := True, cache := False) {
return ImagePut("Window", image, title, pos, style, styleEx, parent, playback, cache)
}
; Shows the image in a window (without a border) 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
; playback - Animate Window? | bool -> True
; cache - Cache Animation Frames? | bool -> False
ImageShow(image, title := "", pos := "", style := 0x90000000, styleEx := 0x80088, parent := "", playback := True, cache := False) {
return ImagePut("Show", image, title, pos, style, styleEx, parent, playback, cache)
}
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 ; Decompresses image to a pixel buffer. Any encoding such as JPG will be lost.
static render := True ; Determines whether vectorized formats such as SVG and PDF are rendered to pixels.
static validate := False ; Always copies pixels to new memory immediately instead of copy-on-read/write.
static call(cotype, image, p*) {
this.gdiplusStartup() ; Start!
coimage := this.convert(cotype, image, p*) ; Convert!
this.gdiplusShutdown(cotype) ; Check if GDI+ is still needed.
return coimage
}
static convert(cotype, image, p*) {
; Take a guess as to what the image might be. (>95% accuracy!)
try type := this.DontVerifyImageType(&image, &keywords)
catch
type := this.ImageType(image)
; Extract options to be directly applied the intermediate representation here.
crop := keywords.HasProp("crop") ? keywords.crop : ""
scale := keywords.HasProp("scale") ? keywords.scale : ""
upscale := keywords.HasProp("upscale") ? keywords.upscale : ""
downscale := keywords.HasProp("downscale") ? keywords.downscale : ""
minsize := keywords.HasProp("minsize") ? keywords.minsize : ""
maxsize := keywords.HasProp("maxsize") ? keywords.maxsize : ""
sprite := keywords.HasProp("sprite") ? keywords.sprite : ""
decode := keywords.HasProp("decode") ? keywords.decode : this.decode
render := keywords.HasProp("render") ? keywords.render : this.render
validate := keywords.HasProp("validate") ? keywords.validate : this.validate
width := keywords.HasProp("width") && keywords.width ~= "^(?!0+$)\d+$" ? keywords.width : ""
height := keywords.HasProp("height") && keywords.height ~= "^(?!0+$)\d+$" ? keywords.height : ""
; Keywords are for (image -> intermediate).
try index := keywords.index
weight := crop || scale || upscale || downscale || minsize || maxsize || sprite || decode
cleanup := ""
if (weight)
goto make_bitmap
; #0 - Special cases.
if (type = "SharedBuffer" && cotype = "SharedBuffer")
return this.SharedBufferToSharedBuffer(image)
if (type = "Monitor" && cotype = "Buffer")
return this.MonitorToBuffer(image)
if (type = "Screenshot" && cotype = "Buffer")
return this.ScreenshotToBuffer(image)
; #1 - Stream as the intermediate representation.
try stream := this.ImageToStream(type, image, keywords)
catch Error as e
if (e.Message ~= "^Conversion from")
goto make_bitmap
else throw
if not stream
throw Error("Stream cannot be zero.")
; Check the file signature for magic numbers.
stream:
(ComCall(Seek := 5, stream, "uint64", 0, "uint", 1, "uint64*", ¤t:=0), current != 0 && MsgBox(current))
extension := this.GetExtensionFromStream(stream)
; Convert vectorized formats to rasterized formats.
if (render && extension ~= "^(?i:pdf|svg)$") {
(extension = "pdf") && this.RenderPDF(&stream, index?)
(extension = "svg") && pBitmap := this.RenderSVG(&stream, width, height)
goto( IsSet(pBitmap) ? "bitmap" : "stream" )
}
; To determine whether the stream should be decoded into pixels:
; (1) Check for scaling or cropping, etc.
; (2) Check if the source encoding is different from the destination.
weight |=
; The 1st parameter holds the destination encoding.
!( cotype ~= "^(?i:safearray|encodedbuffer|hex|base64|uri|stream|randomaccessstream|)$"
&& (!p.Has(1) || p[1] == "" || p[1] = extension && !(extension = "jpg" && p.Has(2) && p[2] != ""))
; The 2nd parameter holds the destination encoding.
|| cotype = "formdata"
&& (!p.Has(2) || p[2] == "" || p[2] = extension && !(extension = "jpg" && p.Has(3) && p[3] != ""))
; Filepaths have the destination encoding as part of the filepath.
|| cotype = "file"
&& (!p.Has(1) || p[1] == "" || p[1] ~= "(^|:|\\|\.)" extension "$" && !(extension = "jpg" && p.Has(2) && p[2] != "")
; If the desired extension is not supported, it is ignored.
|| !(RegExReplace(p[1], "^.*(?:^|:|\\|\.)(.*)$", "$1")
~= "^(?i:avif|avifs|bmp|dib|rle|gif|heic|heif|hif|jpg|jpeg|jpe|jfif|png|tif|tiff)$"))
; Pass through all functions that don't specify an extension.
|| cotype ~= "^(?i:clipboard|url|explorer)")
; MsgBox weight ? "convert to pixels" : "stay as stream"
if weight
goto clean_stream
; Attempt conversion using StreamToCoimage.
try coimage := this.StreamToCoimage(cotype, stream, p*)
catch Error as e
if (e.Message ~= "^Conversion from")
goto clean_stream
else throw
; Clean up the copy. Export raw pointers if requested.
if (cotype != "stream")
ObjRelease(stream)
return coimage
; Otherwise export the image as a stream.
clean_stream:
type := "stream"
image := stream
cleanup := "stream"
; #2 - Fallback to GDI+ bitmap as the intermediate.
make_bitmap:
if !(pBitmap := this.ImageToBitmap(type, image, keywords))
throw Error("pBitmap cannot be zero.")
; GdipImageForceValidation must be called immediately or it fails silently.
bitmap:
outDimensions := [] ; Initialize width x height array
(validate) && DllCall("gdiplus\GdipImageForceValidation", "ptr", pBitmap)
(crop) && this.BitmapCrop(&pBitmap, crop)
(scale) && this.BitmapScale(&pBitmap, scale,,,, outDimensions)
(upscale) && this.BitmapScale(&pBitmap, upscale, 1,,, outDimensions)
(downscale) && this.BitmapScale(&pBitmap, downscale, -1,,, outDimensions)
(minsize) && this.BitmapScale(&pBitmap, minsize, 1, "join", True, outDimensions)
(maxsize) && this.BitmapScale(&pBitmap, maxsize, -1, "meet", True, outDimensions)
(outDimensions.length == 2) && this.BitmapScale(&pBitmap, outDimensions) ; Scale only once
(sprite) && this.BitmapSprite(&pBitmap)
; Save frame delays and loop count for webp.
if (type = "stream" && extension = "webp" && cotype ~= "^(?i:show|window|desktop)$") {
this.ParseWEBP(stream, &pDelays, &pCount)
IsSet(pDelays) && DllCall("gdiplus\GdipSetPropertyItem", "ptr", pBitmap, "ptr", pDelays)
IsSet(pCount) && DllCall("gdiplus\GdipSetPropertyItem", "ptr", pBitmap, "ptr", pCount)
}
; Attempt conversion using BitmapToCoimage.
coimage := this.BitmapToCoimage(cotype, pBitmap, p*)
; Clean up the copy. Export raw pointers if requested.
if (cotype != "bitmap")
DllCall("gdiplus\GdipDisposeImage", "ptr", pBitmap)
if (cleanup = "stream")
ObjRelease(stream)
return coimage
}
static Inputs :=
[
"ClipboardPNG",
"Clipboard",
"SafeArray",
"Screenshot",
"Window",
"Object",
"EncodedBuffer",
"Buffer",
"Monitor",
"Desktop",
"Wallpaper",
"Cursor",
"URL",
"File",
"SharedBuffer",
"Hex",
"Base64",
"DC",
"HBitmap",
"HIcon",
"Bitmap",
"Stream",
"RandomAccessStream",
"WICBitmap",
"D2DBitmap"
]
static DontVerifyImageType(&image, &keywords := "") {
; Sentinel value.
keywords := {}
; Try ImageType.
if !IsObject(image)
throw Error("Must be an object.")
; Goto ImageType.
if image.HasProp("image") && !image.HasMethod("image") {
keywords := image
image := image.image
throw Error("Must catch this error with ImageType.")
}
; Skip ImageType.
for type in this.inputs
if image.HasProp(type) && !image.HasMethod(type) {
keywords := image
image := image.%type%
return type
}
; Continue ImageType.
throw Error("Invalid type.")
}
static ImageType(image) {
if not IsObject(image)
goto string
if image.HasProp("prototype") && image.prototype.HasProp("__class") && image.prototype.__class == "ClipboardAll"
or Type(image) == "ClipboardAll" && this.IsClipboard(image.ptr, image.size)
; A "clipboardpng" is a pointer to a PNG stream saved as the "png" clipboard format.
if DllCall("IsClipboardFormatAvailable", "uint", DllCall("RegisterClipboardFormat", "str", "png", "uint"))
return "ClipboardPNG"
; A "clipboard" is a handle to a GDI bitmap saved as CF_BITMAP.
else if DllCall("IsClipboardFormatAvailable", "uint", 2)
return "Clipboard"
else throw Error("Clipboard format not supported.")
array:
; A "safearray" is a pointer to a SafeArray COM Object.
if ComObjType(image) and ComObjType(image) & 0x2000
return "SafeArray"
; A "screenshot" is an array of 4 numbers with an optional window.
if image.HasProp("__Item") && image.HasProp("length") && image.length ~= "^(4|5)$"
&& image[1] ~= "^-?\d+$" && image[2] ~= "^-?\d+$" && image[3] ~= "^(?!0+$)\d+$" && image[4] ~= "^(?!0+$)\d+$"
&& image[1] > -65536 && image[1] < 65536 && image[2] > -65536 && image[2] < 65536 && image[3] < 65536 && image[4] < 65536
&& (image.Has(5) ? WinExist(image[5]) : True)
return "Screenshot"
object:
; A "window" is an object with an hwnd property.
if image.HasProp("hwnd")
return "Window"
; A "object" has a pBitmap property that points to an internal GDI+ bitmap.
if image.HasProp("pBitmap")
try if !DllCall("gdiplus\GdipGetImageType", "ptr", image.pBitmap, "ptr*", &_type:=0) && (_type == 1)
return "Object"
if not image.HasProp("ptr")
goto end
; Check if image is a pointer. If not, crash and do not recover.
("POINTER IS BAD AND PROGRAM IS CRASH") && NumGet(image.ptr, "char")
; An "encodedbuffer" contains a pointer to the bytes of an encoded image format.
if image.HasProp("ptr") && image.HasProp("size") && this.IsImage(image.ptr, image.size)
return "EncodedBuffer"
; A "buffer" is an object with a pointer to bytes and properties to determine its 2-D shape.
if image.HasProp("ptr")
and ( image.HasProp("width") && image.HasProp("height")
or image.HasProp("stride") && image.HasProp("height")
or image.HasProp("size") && (image.HasProp("stride") || image.HasProp("width") || image.HasProp("height")))
return "Buffer"
image := image.ptr
goto pointer
string:
if (image == "")
throw Error("Image data is an empty string.")
; 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 "url" satisfies the url format.
if this.IsURL(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 "sharedbuffer" is a file mapping kernel object.
if DllCall("CloseHandle", "ptr", DllCall("OpenFileMapping", "uint", 2, "int", 0, "str", "ImagePut_" image, "ptr"))
return "SharedBuffer"
; 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"
; For more helpful error messages: Catch file names without extensions!
if not (image ~= "^-?\d+$") {
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!", -4)
speculate := RegExReplace(image, "(\.[^.]*)?$") "." extension
if FileExist(speculate)
throw Error("Is it possible you meant to type " speculate " as the file extension instead?", -4)
}
goto end
}
handle:
; 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"
; Check if image is a pointer. If not, crash and do not recover.
("POINTER IS BAD AND PROGRAM IS CRASH") && NumGet(image, "char")
; A "bitmap" is a pointer to a GDI+ Bitmap. GdiplusStartup exception is caught above.
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 on 64-bit systems.
; 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.
(A_PtrSize == 8) && ObjRelease(image) ; Therefore do not move this, it has been tested.
pointer:
; 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"
end:
throw Error("Image type could not be identified.")
}
static ImageToBitmap(type, image, keywords := "") {
try index := keywords.index
if (type = "Object")
return this.BitmapToBitmap(image.pBitmap)
if (type = "Clipboard")
return this.ClipboardToBitmap()
if (type = "ClipboardPNG")
return this.ClipboardPNGToBitmap()
if (type = "SafeArray")
return this.SafeArrayToBitmap(image)
if (type = "EncodedBuffer")
return this.EncodedBufferToBitmap(image)
if (type = "SharedBuffer")
return this.SharedBufferToBitmap(image)
if (type = "Buffer")
return this.BufferToBitmap(image)
if (type = "Monitor")
return this.MonitorToBitmap(image)
if (type = "Screenshot")
return this.ScreenshotToBitmap(image)
if (type = "Window")
return this.WindowToBitmap(image)
if (type = "Desktop")
return this.DesktopToBitmap()
if (type = "Wallpaper")
return this.WallpaperToBitmap()
if (type = "Cursor")
return this.CursorToBitmap()
if (type = "URL")
return this.URLToBitmap(image)
if (type = "File")
return this.FileToBitmap(image)
if (type = "Hex")
return this.HexToBitmap(image)
if (type = "Base64")
return this.Base64ToBitmap(image)
if (type = "DC")
return this.DCToBitmap(image)
if (type = "HBitmap")
return this.HBitmapToBitmap(image)
if (type = "HIcon")
return this.HIconToBitmap(image)
if (type = "Bitmap")
return this.BitmapToBitmap(image)
if (type = "Stream")
return this.StreamToBitmap(image)
if (type = "RandomAccessStream")
return this.RandomAccessStreamToBitmap(image)
if (type = "WICBitmap")
return this.WICBitmapToBitmap(image)
if (type = "D2DBitmap")
return this.D2DBitmapToBitmap(image)
throw Error("Conversion from " type " to bitmap is not supported.")
}
static BitmapToCoimage(cotype, pBitmap, p1:="", p2:="", p3:="", p4:="", p5:="", p6:="", p7:="", p*) {
if (cotype = "Clipboard") ; (pBitmap)
return this.BitmapToClipboard(pBitmap)
if (cotype = "SafeArray") ; (pBitmap, extension, quality)
return this.BitmapToSafeArray(pBitmap, p1, p2)
if (cotype = "EncodedBuffer") ; (pBitmap, extension, quality)
return this.BitmapToEncodedBuffer(pBitmap, p1, p2)
if (cotype = "SharedBuffer") ; (pBitmap, name)
return this.BitmapToSharedBuffer(pBitmap, p1)
if (cotype = "Buffer") ; (pBitmap)
return this.BitmapToBuffer(pBitmap)
if (cotype = "Screenshot") ; (pBitmap, pos, alpha)
return this.BitmapToScreenshot(pBitmap, p1, p2)
if (cotype = "Window") ; (pBitmap, title, pos, style, styleEx, parent, playback, cache)
return this.BitmapToWindow(pBitmap, p1, p2, p3, p4, p5, p6, p7)
if (cotype = "Show") ; (pBitmap, title, pos, style, styleEx, parent, playback, cache)
return this.Show(pBitmap, p1, p2, p3, p4, p5, p6, p7)
if (cotype = "Desktop") ; (pBitmap, title, pos, style, styleEx, parent, playback, cache)
return this.BitmapToDesktop(pBitmap, p1, p2, p3, p4, p5, p6, p7)
if (cotype = "Wallpaper") ; (pBitmap)
return this.BitmapToWallpaper(pBitmap)
if (cotype = "Cursor") ; (pBitmap, xHotspot, yHotspot)
return this.BitmapToCursor(pBitmap, p1, p2)
if (cotype = "URL") ; (pBitmap)
return this.BitmapToURL(pBitmap)
if (cotype = "Explorer") ; (pBitmap, default_dir, inactive)
return this.BitmapToExplorer(pBitmap, p1, p2)
if (cotype = "File") ; (pBitmap, filepath, quality)
return this.BitmapToFile(pBitmap, p1, p2)
if (cotype = "Hex") ; (pBitmap, extension, quality)
return this.BitmapToHex(pBitmap, p1, p2)
if (cotype = "Base64") ; (pBitmap, extension, quality)
return this.BitmapToBase64(pBitmap, p1, p2)
if (cotype = "URI") ; (pBitmap, extension, quality)
return this.BitmapToURI(pBitmap, p1, p2)
if (cotype = "DC") ; (pBitmap, alpha)
return this.BitmapToDC(pBitmap, p1)
if (cotype = "HBitmap") ; (pBitmap, alpha)
return this.BitmapToHBitmap(pBitmap, p1)
if (cotype = "HIcon") ; (pBitmap)
return this.BitmapToHIcon(pBitmap)
if (cotype = "Bitmap")
return pBitmap
if (cotype = "Stream") ; (pBitmap, extension, quality)
return this.BitmapToStream(pBitmap, p1, p2)
if (cotype = "RandomAccessStream") ; (pBitmap, extension, quality)
return this.BitmapToRandomAccessStream(pBitmap, p1, p2)
if (cotype = "WICBitmap") ; (pBitmap)
return this.BitmapToWICBitmap(pBitmap)
if (cotype = "D2DBitmap") ; (pBitmap)
return this.BitmapToD2DBitmap(pBitmap)
if (cotype = "FormData") ; (pBitmap, boundary, extension, quality)
return this.BitmapToFormData(pBitmap, p1, p2, p3)
throw Error("Conversion from bitmap to " cotype " is not supported.")
}
static ImageToStream(type, image, keywords := "") {
try index := keywords.index
if (type = "ClipboardPNG")
return this.ClipboardPNGToStream()
if (type = "SafeArray")
return this.SafeArrayToStream(image)
if (type = "EncodedBuffer")
return this.EncodedBufferToStream(image)
if (type = "URL")
return this.URLToStream(image)
if (type = "File")
return this.FileToStream(image)
if (type = "Hex")
return this.HexToStream(image)
if (type = "Base64")
return this.Base64ToStream(image)
if (type = "Stream")
return this.StreamToStream(image)
if (type = "RandomAccessStream")
return this.RandomAccessStreamToStream(image)
throw Error("Conversion from " type " to stream is not supported.")
}
static StreamToCoimage(cotype, stream, p1 := "", p2 := "", p*) {
if (cotype = "Clipboard") ; (stream)
return this.StreamToClipboard(stream)
if (cotype = "SafeArray") ; (stream)
return this.StreamToSafeArray(stream)
if (cotype = "EncodedBuffer") ; (stream)
return this.StreamToEncodedBuffer(stream)
if (cotype = "URL") ; (stream)
return this.StreamToURL(stream)
if (cotype = "Explorer") ; (stream, default_dir, inactive)
return this.StreamToExplorer(stream, p1, p2)
if (cotype = "File") ; (stream, filepath)
return this.StreamToFile(stream, p1)
if (cotype = "Hex") ; (stream)
return this.StreamToHex(stream)
if (cotype = "Base64") ; (stream)
return this.StreamToBase64(stream)
if (cotype = "URI") ; (stream)
return this.StreamToURI(stream)
if (cotype = "Stream")
return stream
if (cotype = "RandomAccessStream") ; (stream)
return this.StreamToRandomAccessStream(stream)
if (cotype = "FormData") ; (stream, boundary)
return this.StreamToFormData(stream, 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 and retain a reference to the backing stream.
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, bound := "", preserveAspectRatio := False, outDimensions := "") {
; min() specifies the greatest lower bound or the maximum size, fitting the image to the bounding box.
; max() specifies the least upper bound or the minimum size, filling the image to the bounding box.
bound := !HasMethod(bound) && (bound ~= "^(?i:fit|meet|and|infimum)$") ? min
: !HasMethod(bound) && (bound ~= "^(?i:fill|join|or|supremum)$") ? max
: !HasMethod(bound) && (bound == "") ? ((direction < 0) ? max : min)
: bound ; Please specify your own bound function
; 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)
; Override the width and height with a previous transform. An empty array can be input to return safe_w and safe_h.
(outDimensions) && outDimensions.Has(1) && width := outDimensions[1]
(outDimensions) && outDimensions.Has(2) && height := outDimensions[2]
; Scale using a real number greater than 0.
if !IsObject(scale) && scale ~= "^(?!0+$)\d+(\.\d+)?$" {
safe_w := Round(width * scale)
safe_h := Round(height * scale)
}
; Specify min or max as the bounding function to fit or fill to the specified edge length.
if Type(scale) == "Array" && scale.length = 1 && scale.Has(1) && scale[1] ~= "^(?!0+$)\d+$" {
safe_w := Round(width * bound(scale[1] / width, scale[1] / height))
safe_h := Round(height * bound(scale[1] / width, scale[1] / height))
}
; (1) If either the width or the height is set to "auto", the other dimension is calculated from the aspect ratio.
; (2) Preserve the aspect ratio using either the width or the height as the reference.
; (3) Scale to the given width x height.
if Type(scale) == "Array" && scale.length = 2 && (scale.Has(1) && scale[1] ~= "^(?!0+$)\d+$" || scale.Has(2) && scale[2] ~= "^(?!0+$)\d+$") {
safe_w := !(scale[1] ~= "^(?!0+$)\d+$") ? Round(width / height * scale[2])
: (preserveAspectRatio) ? Round(width * bound(scale[1] / width, scale[2] / height))
: scale[1]
safe_h := !(scale[2] ~= "^(?!0+$)\d+$") ? Round(height / width * scale[1])
: (preserveAspectRatio) ? Round(height * bound(scale[1] / width, scale[2] / height))
: scale[2]
}
if Type(scale) == "Array" && scale.length = 1 && scale.Has(1) && scale[1] ~= "^(?!0+$)\d+$" && direction = 0
throw Error("Single scale value requires a direction such as upscale or downscale.")
if !IsSet(safe_w) || !IsSet(safe_h)
throw Error("Invalid scale.")
; Force upscaling or downscaling.
if (direction > 0 and (safe_w < width && safe_h < height)) ; upscaling
or (direction < 0 and (safe_w > width && safe_h > height)) ; downscaling
safe_w := width, safe_h := height
; Minimum size is 1 x 1.
safe_w := max(1, safe_w)
safe_h := max(1, safe_h)
; if outDimensions is set, then avoid modifying the bitmap at all. Instead, update the final dimensions in the out parameter.
if (outDimensions) {
outDimensions.length := 2
outDimensions[1] := safe_w
outDimensions[2] := safe_h
return pBitmap
}
; Avoid drawing if no changes detected.
if (safe_w = width && safe_h = height)
return pBitmap
; Create a destination GDI+ Bitmap that owns its memory.
DllCall("gdiplus\GdipCreateBitmapFromScan0", "int", safe_w, "int", safe_h, "int", 0, "int", format, "ptr", 0, "ptr*", &pBitmapScale:=0)
; Create a graphics context as the rendering destination.
DllCall("gdiplus\GdipGetImageGraphicsContext", "ptr", pBitmapScale, "ptr*", &pGraphics:=0)
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, "uint", 0, "int", 0) ; 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)
; Cleanup!
DllCall("gdiplus\GdipDeleteGraphics", "ptr", pGraphics)
DllCall("gdiplus\GdipDisposeImage", "ptr", pBitmap)
return pBitmap := pBitmapScale
}
static BitmapSprite(&pBitmap) {
; Get Bitmap width and height.
DllCall("gdiplus\GdipGetImageWidth", "ptr", pBitmap, "uint*", &width:=0)
DllCall("gdiplus\GdipGetImageHeight", "ptr", pBitmap, "uint*", &height:=0)
; Describes the portion of the bitmap to be cropped. Matches the dimensions of the buffer.
rect := Buffer(16, 0) ; sizeof(rect) = 16
NumPut( "uint", width, rect, 8) ; Width
NumPut( "uint", height, rect, 12) ; Height
; (Type 3) Expose the pixel buffer for modification.
BitmapData := Buffer(16+2*A_PtrSize, 0) ; sizeof(BitmapData) = 24, 32
DllCall("gdiplus\GdipBitmapLockBits"
, "ptr", pBitmap
, "ptr", rect
, "uint", 3 ; ImageLockMode.ReadWrite
, "int", 0x26200A ; Buffer: Format32bppArgb
, "ptr", BitmapData)
Scan0 := NumGet(BitmapData, 16, "ptr")
; C source code - https://godbolt.org/z/nrv5Yr3Y3
static code := 0
if !code {
b64 := (A_PtrSize == 4)
? "VYnli0UIi1UMi00QOdBzDzkIdQbHAAAAAACDwATr7V3D"
: "SDnRcw9EOQF1BDHAiQFIg8EE6+zD"