-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathGD.pd
1958 lines (1569 loc) · 56.9 KB
/
GD.pd
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
#
# GD.pd
#
# PDL interface to the GD c library
# ('cos looping over an ndarray in perl and using the perl GD lib is too slow...)
#
# Judd Taylor, USF IMaRS
# 13 March 2003
#
use strict;
use warnings;
#use PDL;
use vars qw( $VERSION );
$VERSION = "2.103";
#####################################
# Start the General Interface Docs: #
#####################################
pp_addpm({ At => 'Top' }, <<'ENDPM');
use strict;
use warnings;
=head1 NAME
PDL::IO::GD - Interface to the GD image library.
=head1 SYNOPSIS
my $pdl = sequence(byte, 30, 30);
write_png($pdl, load_lut($lutfile), "test.png");
write_true_png(sequence(100, 100, 3), "test_true.png");
my $image = read_png("test.png");
my $image = read_true_png("test_true_read.png");
write_true_png($image, "test_true_read.out.png");
my $lut = read_png_lut("test.png");
$pdl = sequence(byte, 30, 30);
write_png_ex($pdl, load_lut($lutfile), "test_nocomp.png", 0);
write_png_ex($pdl, load_lut($lutfile), "test_bestcomp1.png", 9);
write_png_best($pdl, load_lut($lutfile), "test_bestcomp2.png");
$pdl = sequence(100, 100, 3);
write_true_png_ex($pdl, "test_true_nocomp.png", 0);
write_true_png_ex($pdl, "test_true_bestcomp1.png", 9);
write_true_png_best($pdl, "test_true_bestcomp2.png");
recompress_png_best("test_recomp_best.png");
=head1 DESCRIPTION
This is the "General Interface" for the PDL::IO::GD library, and is actually several
years old at this point (read: stable). If you're feeling frisky, try the new OO
interface described below.
The general version just provides several image IO utility functions you can use with
ndarray variables. It's deceptively useful, however.
=cut
ENDPM
###########################
# General Interface Code: #
###########################
# needed header files:
pp_addhdr(<<'EOH');
#include "gd.h"
#include "gdfontl.h"
#include "gdfonts.h"
#include "gdfontmb.h"
#include "gdfontg.h"
#include "gdfontt.h"
#include <stdio.h>
#define PKG "PDL::IO::GD"
EOH
my %gdi_from_pngfile = (
OtherPars => 'char* filename',
Comp => 'gdImagePtr im',
MakeComp => '
FILE *fh = fopen($COMP(filename), "rb");
if (!fh) $CROAK("Error opening %s\n", $COMP(filename));
$COMP(im) = gdImageCreateFromPng(fh);
fclose(fh);
if (!$COMP(im)) $CROAK("Error reading PNG data\n");
',
CompFreeCodeComp => 'gdImageDestroy($COMP(im));',
);
my %gdi_from_args = (
OtherPars => 'gdImagePtr im',
);
my %lu_dim_check = (
RedoDimsCode => <<'EOF',
if ($SIZE(j) > 256)
$CROAK("Wrong LUT dimensions (%"IND_FLAG", %"IND_FLAG")! (should be (3, X), where X <= 256)\n",
$SIZE(i), $SIZE(j) );
EOF
);
my %level_check = (
RedoDimsCode => <<'EOF',
if( $COMP(level) < -1 || $COMP(level) > 9 )
$CROAK("Invalid compression level %d, should be [-1,9]\n",
$COMP(level) );
EOF
);
my %lu_dim_level_check = (
RedoDimsCode => $lu_dim_check{RedoDimsCode}.$level_check{RedoDimsCode},
);
my $gdi_from_dims = "gdImagePtr im = gdImageCreate(\$SIZE(x), \$SIZE(y));\n";
my $gdi_to_file = <<'EOF';
FILE *out = fopen($COMP(filename), "wb");
if (!out) $CROAK("Error opening %s\n", $COMP(filename));
gdImagePng(im, out);
fclose(out);
gdImageDestroy(im);
EOF
my $gdi_to_fileEx = <<'EOF';
FILE *out = fopen($COMP(filename), "wb");
if (!out) $CROAK("Error opening %s\n", $COMP(filename));
gdImagePngEx(im, out, $COMP(level));
fclose(out);
gdImageDestroy(im);
EOF
my $gdiTrue_from_dims = "gdImagePtr im = gdImageCreateTrueColor(\$SIZE(x), \$SIZE(y));\n";
my $lut_allocate = <<'EOF';
loop(j) %{
int tmp = gdImageColorAllocate(im, $lut(i=>0), $lut(i=>1), $lut(i=>2));
if (tmp != j)
$CROAK("palette mismatch on index %"IND_FLAG" (mapped to %d)\n", j, tmp);
%}
EOF
my $img_to_gdi = 'loop(y,x) %{
if ($img() >= $SIZE(j))
$CROAK("Pixel value=%d exceeded LUT size", (int)$img());
gdImageSetPixel(im, x, y, $img());
%}';
my $img_to_gdiTrue = <<'EOF';
loop(y,x) %{
gdImageSetPixel(im, x, y,
gdImageColorResolve(im, $img(z=>0), $img(z=>1), $img(z=>2))
);
%}
EOF
my $gdi_to_img_tpl = 'loop(y,x) %%{ $img() = gdImageGetPixel($COMP(im), x, %sy); %%}';
my $gdi_to_img = sprintf $gdi_to_img_tpl, '';
my $gdi_to_img_inv = sprintf $gdi_to_img_tpl, '$SIZE(y)-1-';
my $gdiTrue_to_img_tpl = <<'EOF';
if (!$COMP(im)->trueColor) $CROAK("Tried to read a non-truecolour image as truecolour");
loop(y,x) %%{
int tpixel = gdImageTrueColorPixel($COMP(im), x, %sy);
$img(z=>0) = gdTrueColorGetRed(tpixel);
$img(z=>1) = gdTrueColorGetGreen(tpixel);
$img(z=>2) = gdTrueColorGetBlue(tpixel);
%%}
EOF
my $gdiTrue_to_img = sprintf $gdiTrue_to_img_tpl, '';
my $gdiTrue_to_img_inv = sprintf $gdiTrue_to_img_tpl, '$SIZE(y)-1-';
my $gdi_to_ptr = '$img_ptr() = PTR2IV(im);';
# Function to write a PNG image from an ndarray variable:
pp_def( 'write_png',
Pars => 'img(x,y); lut(i=3,j);',
GenericTypes => ['B'],
OtherPars => 'char* filename',
Doc => <<'ENDDOC',
Writes a 2-d PDL variable out to a PNG file, using the supplied color look-up-table ndarray
(hereafter referred to as a LUT).
The LUT contains a line for each value 0-255 with a corresponding R, G, and B value.
ENDDOC
%lu_dim_check,
Code => $gdi_from_dims . $lut_allocate . $img_to_gdi . $gdi_to_file,
);
# Function to write a PNG image from an ndarray variable, accepting a compression
# level argument:
pp_def( 'write_png_ex',
Pars => 'img(x,y); lut(i=3,j);',
GenericTypes => ['B'],
OtherPars => 'char* filename; int level',
Doc => <<'ENDDOC',
Same as write_png(), except you can specify the compression level (0-9) as the last argument.
ENDDOC
%lu_dim_level_check,
Code => $gdi_from_dims . $lut_allocate . $img_to_gdi . $gdi_to_fileEx,
);
# Function to write a TRUE COLOR PNG image from an ndarray variable:
pp_def( 'write_true_png',
Pars => 'img(x,y,z=3);',
GenericTypes => ['B'],
OtherPars => 'char* filename',
Doc => <<'ENDDOC',
Writes an (x, y, z(3)) PDL variable out to a PNG file, using a true color format.
This means a larger file on disk, but can contain more than 256 colors.
ENDDOC
Code => $gdiTrue_from_dims . $img_to_gdiTrue . $gdi_to_file,
);
# Function to write a TRUE COLOR PNG image from an ndarray variable,
# with the specified compression level:
pp_def( 'write_true_png_ex',
Pars => 'img(x,y,z=3);',
GenericTypes => ['B'],
OtherPars => 'char* filename; int level',
Doc => <<'ENDDOC',
Same as write_true_png(), except you can specify the compression level (0-9) as the last argument.
ENDDOC
%level_check,
Code => $gdiTrue_from_dims . $img_to_gdiTrue . $gdi_to_fileEx,
);
#
# Add some perl level alias functions to automatically use the best compression
#
pp_addpm(<<'ENDPM');
=head2 write_png_best
Like write_png(), but it assumes the best PNG compression (9).
=for example
write_png_best( $img(ndarray), $lut(ndarray), $filename )
=cut
sub write_png_best
{
my $img = shift;
my $lut = shift;
my $filename = shift;
return write_png_ex( $img, $lut, $filename, 9 );
} # End of write_png_best()...
=head2 write_true_png_best
Like write_true_png(), but it assumes the best PNG compression (9).
=for example
write_true_png_best( $img(ndarray), $filename )
=cut
sub write_true_png_best
{
my $img = shift;
my $filename = shift;
return write_true_png_ex( $img, $filename, 9 );
} # End of write_true_png_best()...
ENDPM
# End of best copression aliases
pp_add_exported( '', 'write_png_best write_true_png_best' );
#
# Function to recompress PNG files with the best compression available:
# NOTE: libgd doesn't return anything, so there's nothing to check!
pp_addpm( '', <<'ENDPM' );
=head2 recompress_png_best( $filename )
Recompresses the given PNG file using the best compression (9).
=cut
ENDPM
pp_addxs( '', <<'ENDXS' );
void
recompress_png_best(char* filename)
CODE:
gdImagePtr im;
FILE* file = fopen(filename, "rb");
if (!file) croak("Error opening %s\n", filename);
im = gdImageCreateFromPng(file);
fclose(file);
file = fopen(filename, "wb");
if (!file) croak("Error opening %s\n", filename);
gdImagePngEx( im, file, 9 );
fclose(file);
gdImageDestroy(im);
ENDXS
pp_add_exported( '', 'recompress_png_best' );
# End of recompress_png_best() XS code...
pp_addpm(<<'EOPM');
=head2 load_lut( $filename )
Loads a color look up table from an ASCII file. returns an ndarray
=cut
sub load_lut {
xchg(byte(cat(rcols(shift))), 0, 1);
}
EOPM
pp_add_exported('', 'load_lut');
pp_def( 'read_true_png',
Pars => '[o] img(x=CALC(gdImageSX($COMP(im))),y=CALC(gdImageSY($COMP(im))),z=3);',
GenericTypes => ['B'],
%gdi_from_pngfile,
Doc => "=for ref\n\nReads a true colour PNG image into a (new) PDL variable.\n",
Code => $gdiTrue_to_img,
);
pp_def( 'read_png',
Pars => '[o] img(x=CALC(gdImageSX($COMP(im))),y=CALC(gdImageSY($COMP(im))));',
GenericTypes => ['L'],
%gdi_from_pngfile,
Doc => "=for ref\n\nReads a (palette) PNG image into a (new) PDL variable.\n",
Code => $gdi_to_img,
);
pp_def( '_gd_image_to_pdl_true',
Pars => '[o] img(x=CALC(gdImageSX($COMP(im))),y=CALC(gdImageSY($COMP(im))),z=3);',
GenericTypes => ['B'],
%gdi_from_args,
Doc => undef,
Code => $gdiTrue_to_img,
);
pp_def( '_gd_image_to_rpic_true',
Pars => '[o] img(z=3,x=CALC(gdImageSX($COMP(im))),y=CALC(gdImageSY($COMP(im))));',
GenericTypes => ['B'],
%gdi_from_args,
Doc => undef,
Code => $gdiTrue_to_img_inv,
);
pp_def( '_gd_image_to_pdl',
Pars => '[o] img(x=CALC(gdImageSX($COMP(im))),y=CALC(gdImageSY($COMP(im))));',
GenericTypes => ['L'],
%gdi_from_args,
Doc => undef,
Code => $gdi_to_img,
);
pp_def( '_gd_image_to_rpic',
Pars => '[o] img(x=CALC(gdImageSX($COMP(im))),y=CALC(gdImageSY($COMP(im))));',
GenericTypes => ['L'],
%gdi_from_args,
Doc => undef,
Code => $gdi_to_img_inv,
);
pp_def( '_pdl_to_gd_image_true',
Pars => 'img(x,y,z=3); indx [o] img_ptr()',
GenericTypes => ['B'],
Doc => undef,
Code => $gdiTrue_from_dims . $img_to_gdiTrue . $gdi_to_ptr,
);
pp_def( '_pdl_to_gd_image_lut',
Pars => 'img(x,y); lut(i=3,j); indx [o] img_ptr()',
GenericTypes => ['B'],
Doc => undef,
%lu_dim_check,
Code => $gdi_from_dims . $lut_allocate . $img_to_gdi . $gdi_to_ptr,
);
pp_def( 'read_png_lut',
Pars => '[o] lut(c=3,i=256);',
GenericTypes => ['B'],
%gdi_from_pngfile,
Doc => "=for ref\n\nReads a color LUT from an already-existing palette PNG file.\n",
Code => <<'EOC',
loop(i) %{
$lut(c=>0) = gdImageRed($COMP(im), i);
$lut(c=>1) = gdImageGreen($COMP(im), i);
$lut(c=>2) = gdImageBlue($COMP(im), i);
%}
EOC
);
pp_def( 'write_gif_anim',
Pars => 'img(c=3,x,y,n)',
GenericTypes => ['B'],
OtherPars => 'char* filename; int Loops; int Delay',
OtherParsDefaults => {Loops=>0, Delay=>4},
NoPthread => 1,
Doc => <<'EOF',
=for ref
Writes an image cube to a file as an animated GIF.
RGB dimension is first. y=0 is at bottom. 0 loops = infinite (default).
Delay in 100ths of a second, default 4.
EOF
Code => <<'EOF',
FILE *fh = fopen($COMP(filename), "wb");
if (!fh) $CROAK("Error opening %s\n", $COMP(filename));
gdImagePtr im = gdImageCreateTrueColor($SIZE(x), $SIZE(y)), im_prev = NULL;
if (!im) $CROAK("Error creating gdImage\n");
loop (n=0:1) %{
loop (y,x) %{
gdImageSetPixel(im, x, $SIZE(y)-1-y,
gdImageColorResolve(im, $img(c=>0), $img(c=>1), $img(c=>2))
);
%}
%}
gdImageGifAnimBegin(im, fh, 0, $COMP(Loops));
gdImageGifAnimAdd(im, fh, 1, 0, 0, $COMP(Delay), gdDisposalNone, im_prev);
im_prev = im;
loop (n=1) %{
im = gdImageCreateTrueColor($SIZE(x), $SIZE(y));
if (!im) $CROAK("Error creating gdImage\n");
loop (y,x) %{
gdImageSetPixel(im, x, $SIZE(y)-1-y,
gdImageColorResolve(im, $img(c=>0), $img(c=>1), $img(c=>2))
);
%}
gdImageGifAnimAdd(im, fh, 1, 0, 0, $COMP(Delay), gdDisposalNone, im_prev);
gdImageDestroy(im_prev);
im_prev = im;
%}
gdImageDestroy(im_prev);
gdImageGifAnimEnd(fh);
fclose(fh);
EOF
);
pp_addxs( <<'ENDXS' );
void
_gdImageDestroy( im )
gdImagePtr im
CODE:
/* fprintf( stderr, "_gdImageDestroy(): gdImagePtr = %p (d=%d x=%x l=%ld ll=%lld)\n", im, im, im, im, im);*/
gdImageDestroy ( im );
OUTPUT:
ENDXS
####################
# NEW OO Interface #
####################
##############################################
# Autogeneration of the low level interface: #
##############################################
##################################################
# Process functions to create images from files: #
##################################################
#########################################
# Start the PDL::IO::GD OO module code: #
#########################################
pp_addpm( { At => 'Bot' }, <<'ENDPM' );
=head1 OO INTERFACE
Object Oriented interface to the GD image library.
=head1 SYNOPSIS
# Open an existing file:
#
my $gd = PDL::IO::GD->new( { filename => "test.png" } );
# Query the x and y sizes:
my $x = $gd->SX();
my $y = $gd->SY();
# Grab the PDL of the data:
my $pdl = $gd->to_pdl; # (x,y,3) y=0 at top
# Grab the PDL of the data:
my $pdl = $gd->to_rpic; # (3,x,y) y=0 at bottom
# Kill this thing:
$gd->DESTROY();
# Create a new object:
#
my $im = PDL::IO::GD->new( { x => 300, y => 300 } );
# Allocate some colors:
#
my $black = $im->ColorAllocate( 0, 0, 0 );
my $red = $im->ColorAllocate( 255, 0, 0 );
my $green = $im->ColorAllocate( 0, 255, 0 );
my $blue = $im->ColorAllocate( 0, 0, 255 );
# Draw a rectangle:
$im->Rectangle( 10, 10, 290, 290, $red );
# Add some text:
$im->String( gdFontGetLarge(), 20, 20, "Test Large Font!", $green );
# Write the output file:
$im->write_Png( "test2.png" );
=head1 DESCRIPTION
This is the Object-Oriented interface from PDL to the GD image library.
See L<http://www.boutell.com/gd/> for more information on the GD library and how it works.
=head2 IMPLEMENTATION NOTES
Surprisingly enough, this interface has nothing to do with the other Perl->GD interface module,
aka 'GD' (as in 'use GD;'). This is done from scratch over the years.
Requires at least version 2.0.22 of the GD library, but it's only been thoroughly tested with
gd-2.0.33, so it would be best to use that. The 2.0.22 requirement has to do with a change in
GD's font handling functions, so if you don't use those, then don't worry about it.
I should also add, the statement about "thoroughly tested" above is mostly a joke. This OO
interface is very young, and it has I<barely> been tested at all, so if something
breaks, email me and I'll get it fixed ASAP (for me).
Functions that manipulate and query the image objects generally have a 'gdImage' prefix on the
function names (ex: gdImageString()). I've created aliases here for all of those member
functions so you don't have to keep typing 'gdImage' in your code, but the long version are in
there as well.
=head1 METHODS
=cut
use PDL;
use PDL::Slices;
use PDL::IO::Misc;
#
# Some helper functions:
#
sub _pkg_name
{ return "PDL::IO::GD::" . (shift) . "()"; }
# ID a file type from it's filename:
sub _id_image_file
{
my $filename = shift;
return 'png'
if( $filename =~ /\.png$/ );
return 'jpg'
if( $filename =~ /\.jpe?g$/ );
return 'wbmp'
if( $filename =~ /\.w?bmp$/ );
return 'gd'
if( $filename =~ /\.gd$/ );
return 'gd2'
if( $filename =~ /\.gd2$/ );
return 'gif'
if( $filename =~ /\.gif$/ );
return 'xbm'
if( $filename =~ /\.xbm$/ );
return undef;
} # End of _id_image_file()...
# Load a new file up (don't read it yet):
sub _img_ptr_from_file
{
my $filename = shift;
my $type = shift;
return _gdImageCreateFromPng( $filename )
if( $type eq 'png' );
return _gdImageCreateFromJpeg( $filename )
if( $type eq 'jpg' );
return _gdImageCreateFromWBMP( $filename )
if( $type eq 'wbmp' );
return _gdImageCreateFromGd( $filename )
if( $type eq 'gd' );
return _gdImageCreateFromGd2( $filename )
if( $type eq 'gd2' );
return _gdImageCreateFromGif( $filename )
if( $type eq 'gif' );
return _gdImageCreateFromXbm( $filename )
if( $type eq 'xbm' );
return undef;
} # End of _img_ptr_from_file()...
# ID a file type from it's "magic" header in the image data:
sub _id_image_data
{
my $data = shift;
my $magic = substr($data,0,4);
return 'png'
if( $magic eq "\x89PNG" );
return 'jpg'
if( $magic eq "\377\330\377\340" );
return 'jpg'
if( $magic eq "\377\330\377\341" );
return 'jpg'
if( $magic eq "\377\330\377\356" );
return 'gif'
if( $magic eq "GIF8" );
return 'gd2'
if( $magic eq "gd2\000" );
# Still need filters for WBMP and .gd!
return undef;
} # End of _id_image_data()...
# Load a new data scalar up:
sub _img_ptr_from_data
{
my $data = shift;
my $type = shift;
return _gdImageCreateFromPngPtr( $data )
if( $type eq 'png' );
return _gdImageCreateFromJpegPtr( $data )
if( $type eq 'jpg' );
return _gdImageCreateFromWBMPPtr( $data )
if( $type eq 'wbmp' );
return _gdImageCreateFromGdPtr( $data )
if( $type eq 'gd' );
return _gdImageCreateFromGd2Ptr( $data )
if( $type eq 'gd2' );
return _gdImageCreateFromGifPtr( $data )
if( $type eq 'gif' );
return undef;
} # End of _img_ptr_from_data()...
=head2 new
Creates a new PDL::IO::GD object.
Accepts a hash describing how to create the object. Accepts a single hash ( with
curly braces ), an inline hash (the same, but without the braces) or a single
string interpreted as a filename. Thus the following are all equivalent:
PDL::IO::GD->new( {filename => 'image.png'} );
PDL::IO::GD->new( filename => 'image.png' );
PDL::IO::GD->new( 'image.png' );
If the hash has:
pdl => $pdl_var (lut => $lut_ndarray)
Then a new GD is created from that PDL variable.
filename => $file
Then a new GD is created from the image file.
x => $num, y => $num
Then a new GD is created as a palette image, with size x, y
x => $num, y => $num, true_color => 1
Then a new GD is created as a true color image, with size x, y
data => $scalar (type => $typename)
Then a new GD is created from the file data stored in $scalar.
If no type is given, then it will try to guess the type of the data, but
this will not work for WBMP and gd image types. For those types, you
_must_ specify the type of the data, or the operation will fail.
Valid types are: 'jpg', 'png', 'gif', 'gd', 'gd2', 'wbmp'.
Example:
my $gd = PDL::IO::GD->new({ pdl => $pdl_var });
my $gd = PDL::IO::GD->new({ pdl => $pdl_var, lut => $lut_ndarray });
my $gd = PDL::IO::GD->new({ filename => "image.png" });
my $gd = PDL::IO::GD->new({ x => 100, y => 100 });
my $gd = PDL::IO::GD->new({ x => 100, y => 100, true_color => 1 });
my $gd = PDL::IO::GD->new({ data => $imageData });
my $gd = PDL::IO::GD->new({ data => $imageData, type => 'wbmp' });
=cut
sub new
{
my $proto = shift;
my $class = ref($proto) || $proto;
#my $self = $class->SUPER::new( @_ );
my $self = {};
my $sub = _pkg_name( "new" );
# Figure out our options:
# I want a single hash. I handle several cases here
my $options;
if( @_ == 1 && ref $_[0] eq 'HASH' ) {
# single hash argument. Just take it
$options = shift;
}
elsif( @_ == 1 && ! ref $_[0] ) {
# single scalar argument. Treat it as a filename by default
my $filename = shift;
$options = { filename => $filename };
}
else {
# the only other acceptable option is an inline hash. This is valid if I
# have an even number of arguments, and the even-indexed ones (the keys)
# are scalars
if( @_ % 2 == 0 ) {
my @pairs = @_;
my $Npairs = scalar(@pairs)/2;
use List::Util 'none';
if( none { ref $pairs[2*$_] } 0..$Npairs-1 ) {
# treat the arguments as a hash
$options = { @pairs }
}
}
}
if( !defined $options ) {
die <<EOF;
PDL::IO::GD::new couldn't parse its arguments.
Expected a hash-ref or an inline hash or just a filename
EOF
}
if( defined( $options->{pdl} ) )
{ # Create it from a PDL variable:
my $pdl = $options->{pdl};
$pdl->make_physical();
my $num_dims = scalar( $pdl->dims() );
if( $num_dims == 2 )
{
if( defined( $options->{lut} ) )
{
die "$sub: _pdl_to_gd_image_lut() failed\n" unless
$self->{IMG_PTR} = _pdl_to_gd_image_lut( $pdl, $options->{lut} )->sclr;
}
else
{
my $lut = sequence(byte, 256)->slice("*3,:");
die "$sub: _pdl_to_gd_image_lut() failed\n" unless
$self->{IMG_PTR} = _pdl_to_gd_image_lut( $pdl, $lut )->sclr;
}
}
elsif( $num_dims == 3 )
{
die "$sub: _pdl_to_gd_image_true() failed\n" unless
$self->{IMG_PTR} = _pdl_to_gd_image_true( $pdl )->sclr;
}
else
{
die "Can't create a PDL::IO::GD from a PDL with bad dims\n";
}
}
elsif( exists( $options->{filename} ) )
{ # Create it from a file:
if( !defined $options->{filename} ) {
die "PDL::IO::GD::new got an undefined filename. Giving up.\n";
}
# Figure out what type of file it is:
$self->{input_type} = _id_image_file( $options->{filename} )
or die "$sub: Can't determine image type of filename => \'$options->{filename}\'\n";
# Read in the file:
$self->{IMG_PTR} = _img_ptr_from_file( $options->{filename}, $self->{input_type} )
or die "$sub: Can't read in the input file\n";
}
elsif( defined( $options->{x} ) && defined( $options->{y} ) )
{ # Create an empty image:
my $done = 0;
if( $options->{true_color} )
{ # Create an empty true color image:
die "$sub: _gdImageCreateTrueColor() failed\n" unless
$self->{IMG_PTR} = _gdImageCreateTrueColor( $options->{x}, $options->{y} );
$done = 1;
}
unless( $done )
{ # Create an empty palette image:
die "$sub: _gdImageCreatePalette() failed\n" unless
$self->{IMG_PTR} = _gdImageCreatePalette( $options->{x}, $options->{y} );
}
}
elsif( defined( $options->{data} ) )
{ # Create an image from the given image data:
# Figure out what type of file it is:
if( defined( $options->{type} ) &&
( $options->{type} eq 'jpg'
|| $options->{type} eq 'png'
|| $options->{type} eq 'gif'
|| $options->{type} eq 'wbmp'
|| $options->{type} eq 'gd'
|| $options->{type} eq 'gd2' ) )
{
$self->{input_type} = $options->{type};
}
else
{
$self->{input_type} = _id_image_data( $options->{data} )
or die "$sub: Can't determine image type given data\n";
}
# Load the data:
$self->{IMG_PTR} = _img_ptr_from_data( $options->{data}, $self->{input_type} )
or die "$sub: Can't load the input image data\n";
}
# Bless and return:
#
bless ($self, $class);
return $self;
} # End of new()...
=head2 to_pdl
When you're done playing with your GDImage and want an ndarray back, use this function to return one.
For true-colour, RGB dim is highest (x,y,3).
To get it in the lowest dim (and with y=0 is the bottom), use L</to_rpic>.
=cut
sub to_pdl {
my $self = shift;
$self->gdImageTrueColor() ? _gd_image_to_pdl_true( $self->{IMG_PTR} )
: _gd_image_to_pdl( $self->{IMG_PTR} );
}
=head2 to_rpic
When you're done playing with your GDImage and want an ndarray back, use this function to return one.
For true-colour, RGB dim is lowest (3,x,y).
To get it in the highest dim (and with y=0 is the top), use L</to_pdl>.
=cut
sub to_rpic {
my $self = shift;
$self->gdImageTrueColor() ? _gd_image_to_rpic_true( $self->{IMG_PTR} )
: _gd_image_to_rpic( $self->{IMG_PTR} );
}
=head2 apply_lut( $lut(ndarray) )
Does a $im->ColorAllocate() for an entire LUT ndarray at once.
The LUT ndarray format is the same as for the general interface above.
=cut
sub apply_lut
{
my $self = shift;
my $lut = shift;
# Let the PDL broadcasting engine sort this out:
$self->ColorAllocates( $lut->slice("(0),:"), $lut->slice("(1),:"), $lut->slice("(2),:") );
} # End of apply_lut()...
sub DESTROY
{
my $self = shift;
my $sub = _pkg_name( "DESTROY" );
#print STDERR sprintf("$sub: destroying gdImagePtr: 0x%p (%d) (%ld) (%lld)\n", $self->{IMG_PTR}, $self->{IMG_PTR},$self->{IMG_PTR},$self->{IMG_PTR});
if( defined( $self->{IMG_PTR} ) )
{
_gdImageDestroy( $self->{IMG_PTR} );
delete( $self->{IMG_PTR} );
}
} # End of DESTROY()...
=head2 WARNING:
All of the docs below this point are auto-generated (not to mention the actual code),
so read with a grain of salt, and B<always> check the main GD documentation about how
that function works and what it does.
=cut
ENDPM
generate_create_functions( <<'ENDCREATE' );
gdImagePtr gdImageCreateFromPng (FILE * fd);
gdImagePtr gdImageCreateFromWBMP (FILE * inFile);
gdImagePtr gdImageCreateFromJpeg (FILE * infile);
gdImagePtr gdImageCreateFromGd (FILE * in);
gdImagePtr gdImageCreateFromGd2 (FILE * in);
gdImagePtr gdImageCreateFromXbm (FILE * in);
gdImagePtr gdImageCreateFromGif (FILE * fd);
gdImagePtr gdImageCreate (int sx, int sy);
gdImagePtr gdImageCreatePalette (int sx, int sy);
gdImagePtr gdImageCreateTrueColor (int sx, int sy);
ENDCREATE
generate_create_from_data_functions( <<'ENDCDATA' );
gdImagePtr gdImageCreateFromPngPtr (int size, void * data);
gdImagePtr gdImageCreateFromWBMPPtr (int size, void * data);
gdImagePtr gdImageCreateFromJpegPtr (int size, void * data);
gdImagePtr gdImageCreateFromGdPtr (int size, void * data);
gdImagePtr gdImageCreateFromGd2Ptr (int size, void * data);
gdImagePtr gdImageCreateFromGifPtr (int size, void * data);
ENDCDATA
generate_write_functions( <<'ENDWRITE' );
void gdImagePng (gdImagePtr im, FILE * out);
void gdImagePngEx (gdImagePtr im, FILE * out, int level);
void gdImageWBMP (gdImagePtr image, int fg, FILE * out);
void gdImageJpeg (gdImagePtr im, FILE * out, int quality);
void gdImageGd (gdImagePtr im, FILE * out);
void gdImageGd2 (gdImagePtr im, FILE * out, int cs, int fmt);
void gdImageGif (gdImagePtr im, FILE * out);
ENDWRITE
generate_data_ptr_functions( <<'ENDDATAPTR' );
void *gdImagePngPtr (gdImagePtr im, int *size);
void *gdImagePngPtrEx (gdImagePtr im, int *size, int level);
void *gdImageWBMPPtr (gdImagePtr im, int *size, int fg);
void *gdImageJpegPtr (gdImagePtr im, int *size, int quality);
void *gdImageGdPtr (gdImagePtr im, int *size);
void *gdImageGd2Ptr (gdImagePtr im, int cs, int fmt, int *size);
ENDDATAPTR
#void gdImageDestroy (gdImagePtr im);
generate_member_functions( <<'ENDMEMBERS' );
void gdImageSetPixel (gdImagePtr im, int x, int y, int color);
int gdImageGetPixel (gdImagePtr im, int x, int y);
void gdImageAABlend (gdImagePtr im);
void gdImageLine (gdImagePtr im, int x1, int y1, int x2, int y2, int color);
void gdImageDashedLine (gdImagePtr im, int x1, int y1, int x2, int y2, int color);
void gdImageRectangle (gdImagePtr im, int x1, int y1, int x2, int y2, int color);
void gdImageFilledRectangle (gdImagePtr im, int x1, int y1, int x2, int y2, int color);
void gdImageSetClip(gdImagePtr im, int x1, int y1, int x2, int y2);
void gdImageGetClip(gdImagePtr im, int *x1P, int *y1P, int *x2P, int *y2P);
int gdImageBoundsSafe (gdImagePtr im, int x, int y);
void gdImageChar (gdImagePtr im, gdFontPtr f, int x, int y, int c, int color);
void gdImageCharUp (gdImagePtr im, gdFontPtr f, int x, int y, int c, int color);
void gdImageString (gdImagePtr im, gdFontPtr f, int x, int y, unsigned char *s, int color);
void gdImageStringUp (gdImagePtr im, gdFontPtr f, int x, int y, unsigned char *s, int color);
void gdImageString16 (gdImagePtr im, gdFontPtr f, int x, int y, unsigned short *s, int color);
void gdImageStringUp16 (gdImagePtr im, gdFontPtr f, int x, int y, unsigned short *s, int color);
void gdImagePolygon (gdImagePtr im, gdPointPtr p, int n, int c);
void gdImageFilledPolygon (gdImagePtr im, gdPointPtr p, int n, int c);
int gdImageColorAllocate (gdImagePtr im, int r, int g, int b);
int gdImageColorAllocateAlpha (gdImagePtr im, int r, int g, int b, int a);
int gdImageColorClosest (gdImagePtr im, int r, int g, int b);
int gdImageColorClosestAlpha (gdImagePtr im, int r, int g, int b, int a);
int gdImageColorClosestHWB (gdImagePtr im, int r, int g, int b);
int gdImageColorExact (gdImagePtr im, int r, int g, int b);
int gdImageColorExactAlpha (gdImagePtr im, int r, int g, int b, int a);
int gdImageColorResolve (gdImagePtr im, int r, int g, int b);
int gdImageColorResolveAlpha (gdImagePtr im, int r, int g, int b, int a);