forked from rmagick-temp/rmagick
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathRMagick.rb
1962 lines (1729 loc) · 60.5 KB
/
RMagick.rb
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
# $Id: RMagick.rb,v 1.84 2009/09/15 22:08:41 rmagick Exp $
#==============================================================================
# Copyright (C) 2009 by Timothy P. Hunter
# Name: RMagick.rb
# Author: Tim Hunter
# Purpose: Extend Ruby to interface with ImageMagick.
# Notes: RMagick2.so defines the classes. The code below adds methods
# to the classes.
#==============================================================================
require 'RMagick2.so'
module Magick
@formats = nil
@trace_proc = nil
@exit_block_set_up = nil
class << self
def formats(&block)
@formats ||= init_formats()
if block_given?
@formats.each { |k,v| yield k, v }
self
else
@formats
end
end
# remove reference to the proc at exit
def trace_proc=(p)
if @trace_proc.nil? && !p.nil? && !@exit_block_set_up
at_exit { @trace_proc = nil }
@exit_block_set_up = true
end
@trace_proc = p
end
end
# Geometry class and related enum constants
class GeometryValue < Enum
# no methods
end
PercentGeometry = GeometryValue.new(:PercentGeometry, 1).freeze
AspectGeometry = GeometryValue.new(:AspectGeometry, 2).freeze
LessGeometry = GeometryValue.new(:LessGeometry, 3).freeze
GreaterGeometry = GeometryValue.new(:GreaterGeometry, 4).freeze
AreaGeometry = GeometryValue.new(:AreaGeometry, 5).freeze
MinimumGeometry = GeometryValue.new(:MinimumGeometry, 6).freeze
class Geometry
FLAGS = ['', '%', '!', '<', '>', '@', '^']
RFLAGS = { '%' => PercentGeometry,
'!' => AspectGeometry,
'<' => LessGeometry,
'>' => GreaterGeometry,
'@' => AreaGeometry,
'^' => MinimumGeometry }
attr_accessor :width, :height, :x, :y, :flag
def initialize(width=nil, height=nil, x=nil, y=nil, flag=nil)
raise(ArgumentError, "width set to #{width.to_s}") if width.is_a? GeometryValue
raise(ArgumentError, "height set to #{height.to_s}") if height.is_a? GeometryValue
raise(ArgumentError, "x set to #{x.to_s}") if x.is_a? GeometryValue
raise(ArgumentError, "y set to #{y.to_s}") if y.is_a? GeometryValue
# Support floating-point width and height arguments so Geometry
# objects can be used to specify Image#density= arguments.
if width == nil
@width = 0
elsif width.to_f >= 0.0
@width = width.to_f
else
Kernel.raise ArgumentError, "width must be >= 0: #{width}"
end
if height == nil
@height = 0
elsif height.to_f >= 0.0
@height = height.to_f
else
Kernel.raise ArgumentError, "height must be >= 0: #{height}"
end
@x = x.to_i
@y = y.to_i
@flag = flag
end
# Construct an object from a geometry string
W = /(\d+\.\d+%?)|(\d*%?)/
H = W
X = /(?:([-+]\d+))?/
Y = X
RE = /\A#{W}x?#{H}#{X}#{Y}([!<>@\^]?)\Z/
def Geometry.from_s(str)
m = RE.match(str)
if m
width = (m[1] || m[2]).to_f
height = (m[3] || m[4]).to_f
x = m[5].to_i
y = m[6].to_i
flag = RFLAGS[m[7]]
else
Kernel.raise ArgumentError, "invalid geometry format"
end
if str['%']
flag = PercentGeometry
end
Geometry.new(width, height, x, y, flag)
end
# Convert object to a geometry string
def to_s
str = ''
if @width > 0
fmt = @width.truncate == @width ? "%d" : "%.2f"
str << sprintf(fmt, @width)
str << '%' if @flag == PercentGeometry
end
if (@width > 0 && @flag != PercentGeometry) || (@height > 0)
str << 'x'
end
if @height > 0
fmt = @height.truncate == @height ? "%d" : "%.2f"
str << sprintf(fmt, @height)
str << '%' if @flag == PercentGeometry
end
str << sprintf("%+d%+d", @x, @y) if (@x != 0 || @y != 0)
if @flag != PercentGeometry
str << FLAGS[@flag.to_i]
end
str
end
end
class Draw
# Thse hashes are used to map Magick constant
# values to the strings used in the primitives.
ALIGN_TYPE_NAMES = {
LeftAlign.to_i => 'left',
RightAlign.to_i => 'right',
CenterAlign.to_i => 'center'
}.freeze
ANCHOR_TYPE_NAMES = {
StartAnchor.to_i => 'start',
MiddleAnchor.to_i => 'middle',
EndAnchor.to_i => 'end'
}.freeze
DECORATION_TYPE_NAMES = {
NoDecoration.to_i => 'none',
UnderlineDecoration.to_i => 'underline',
OverlineDecoration.to_i => 'overline',
LineThroughDecoration.to_i => 'line-through'
}.freeze
FONT_WEIGHT_NAMES = {
AnyWeight.to_i => 'all',
NormalWeight.to_i => 'normal',
BoldWeight.to_i => 'bold',
BolderWeight.to_i => 'bolder',
LighterWeight.to_i => 'lighter',
}.freeze
GRAVITY_NAMES = {
NorthWestGravity.to_i => 'northwest',
NorthGravity.to_i => 'north',
NorthEastGravity.to_i => 'northeast',
WestGravity.to_i => 'west',
CenterGravity.to_i => 'center',
EastGravity.to_i => 'east',
SouthWestGravity.to_i => 'southwest',
SouthGravity.to_i => 'south',
SouthEastGravity.to_i => 'southeast'
}.freeze
PAINT_METHOD_NAMES = {
PointMethod.to_i => 'point',
ReplaceMethod.to_i => 'replace',
FloodfillMethod.to_i => 'floodfill',
FillToBorderMethod.to_i => 'filltoborder',
ResetMethod.to_i => 'reset'
}.freeze
STRETCH_TYPE_NAMES = {
NormalStretch.to_i => 'normal',
UltraCondensedStretch.to_i => 'ultra-condensed',
ExtraCondensedStretch.to_i => 'extra-condensed',
CondensedStretch.to_i => 'condensed',
SemiCondensedStretch.to_i => 'semi-condensed',
SemiExpandedStretch.to_i => 'semi-expanded',
ExpandedStretch.to_i => 'expanded',
ExtraExpandedStretch.to_i => 'extra-expanded',
UltraExpandedStretch.to_i => 'ultra-expanded',
AnyStretch.to_i => 'all'
}.freeze
STYLE_TYPE_NAMES = {
NormalStyle.to_i => 'normal',
ItalicStyle.to_i => 'italic',
ObliqueStyle.to_i => 'oblique',
AnyStyle.to_i => 'all'
}.freeze
private
def enquote(str)
if str.length > 2 && /\A(?:\"[^\"]+\"|\'[^\']+\'|\{[^\}]+\})\z/.match(str)
return str
else
return '"' + str + '"'
end
end
public
# Apply coordinate transformations to support scaling (s), rotation (r),
# and translation (t). Angles are specified in radians.
def affine(sx, rx, ry, sy, tx, ty)
primitive "affine " + sprintf("%g,%g,%g,%g,%g,%g", sx, rx, ry, sy, tx, ty)
end
# Draw an arc.
def arc(startX, startY, endX, endY, startDegrees, endDegrees)
primitive "arc " + sprintf("%g,%g %g,%g %g,%g",
startX, startY, endX, endY, startDegrees, endDegrees)
end
# Draw a bezier curve.
def bezier(*points)
if points.length == 0
Kernel.raise ArgumentError, "no points specified"
elsif points.length % 2 != 0
Kernel.raise ArgumentError, "odd number of arguments specified"
end
primitive "bezier " + points.join(',')
end
# Draw a circle
def circle(originX, originY, perimX, perimY)
primitive "circle " + sprintf("%g,%g %g,%g", originX, originY, perimX, perimY)
end
# Invoke a clip-path defined by def_clip_path.
def clip_path(name)
primitive "clip-path #{name}"
end
# Define the clipping rule.
def clip_rule(rule)
if ( not ["evenodd", "nonzero"].include?(rule.downcase) )
Kernel.raise ArgumentError, "Unknown clipping rule #{rule}"
end
primitive "clip-rule #{rule}"
end
# Define the clip units
def clip_units(unit)
if ( not ["userspace", "userspaceonuse", "objectboundingbox"].include?(unit.downcase) )
Kernel.raise ArgumentError, "Unknown clip unit #{unit}"
end
primitive "clip-units #{unit}"
end
# Set color in image according to specified colorization rule. Rule is one of
# point, replace, floodfill, filltoborder,reset
def color(x, y, method)
if ( not PAINT_METHOD_NAMES.has_key?(method.to_i) )
Kernel.raise ArgumentError, "Unknown PaintMethod: #{method}"
end
primitive "color #{x},#{y},#{PAINT_METHOD_NAMES[method.to_i]}"
end
# Specify EITHER the text decoration (none, underline, overline,
# line-through) OR the text solid background color (any color name or spec)
def decorate(decoration)
if ( DECORATION_TYPE_NAMES.has_key?(decoration.to_i) )
primitive "decorate #{DECORATION_TYPE_NAMES[decoration.to_i]}"
else
primitive "decorate #{enquote(decoration)}"
end
end
# Define a clip-path. A clip-path is a sequence of primitives
# bracketed by the "push clip-path <name>" and "pop clip-path"
# primitives. Upon advice from the IM guys, we also bracket
# the clip-path primitives with "push(pop) defs" and "push
# (pop) graphic-context".
def define_clip_path(name)
begin
push('defs')
push('clip-path', name)
push('graphic-context')
yield
ensure
pop('graphic-context')
pop('clip-path')
pop('defs')
end
end
# Draw an ellipse
def ellipse(originX, originY, width, height, arcStart, arcEnd)
primitive "ellipse " + sprintf("%g,%g %g,%g %g,%g",
originX, originY, width, height, arcStart, arcEnd)
end
# Let anything through, but the only defined argument
# is "UTF-8". All others are apparently ignored.
def encoding(encoding)
primitive "encoding #{encoding}"
end
# Specify object fill, a color name or pattern name
def fill(colorspec)
primitive "fill #{enquote(colorspec)}"
end
alias fill_color fill
alias fill_pattern fill
# Specify fill opacity (use "xx%" to indicate percentage)
def fill_opacity(opacity)
primitive "fill-opacity #{opacity}"
end
def fill_rule(rule)
if ( not ["evenodd", "nonzero"].include?(rule.downcase) )
Kernel.raise ArgumentError, "Unknown fill rule #{rule}"
end
primitive "fill-rule #{rule}"
end
# Specify text drawing font
def font(name)
primitive "font #{name}"
end
def font_family(name)
primitive "font-family \'#{name}\'"
end
def font_stretch(stretch)
if ( not STRETCH_TYPE_NAMES.has_key?(stretch.to_i) )
Kernel.raise ArgumentError, "Unknown stretch type"
end
primitive "font-stretch #{STRETCH_TYPE_NAMES[stretch.to_i]}"
end
def font_style(style)
if ( not STYLE_TYPE_NAMES.has_key?(style.to_i) )
Kernel.raise ArgumentError, "Unknown style type"
end
primitive "font-style #{STYLE_TYPE_NAMES[style.to_i]}"
end
# The font weight argument can be either a font weight
# constant or [100,200,...,900]
def font_weight(weight)
if ( FONT_WEIGHT_NAMES.has_key?(weight.to_i) )
primitive "font-weight #{FONT_WEIGHT_NAMES[weight.to_i]}"
else
primitive "font-weight #{weight}"
end
end
# Specify the text positioning gravity, one of:
# NorthWest, North, NorthEast, West, Center, East, SouthWest, South, SouthEast
def gravity(grav)
if ( not GRAVITY_NAMES.has_key?(grav.to_i) )
Kernel.raise ArgumentError, "Unknown text positioning gravity"
end
primitive "gravity #{GRAVITY_NAMES[grav.to_i]}"
end
# IM 6.5.5-8 and later
def interline_spacing(space)
begin
Float(space)
rescue ArgumentError
Kernel.raise ArgumentError, "invalid value for interline_spacing"
rescue TypeError
Kernel.raise TypeError, "can't convert #{space.class} into Float"
end
primitive "interline-spacing #{space}"
end
# IM 6.4.8-3 and later
def interword_spacing(space)
begin
Float(space)
rescue ArgumentError
Kernel.raise ArgumentError, "invalid value for interword_spacing"
rescue TypeError
Kernel.raise TypeError, "can't convert #{space.class} into Float"
end
primitive "interword-spacing #{space}"
end
# IM 6.4.8-3 and later
def kerning(space)
begin
Float(space)
rescue ArgumentError
Kernel.raise ArgumentError, "invalid value for kerning"
rescue TypeError
Kernel.raise TypeError, "can't convert #{space.class} into Float"
end
primitive "kerning #{space}"
end
# Draw a line
def line(startX, startY, endX, endY)
primitive "line " + sprintf("%g,%g %g,%g", startX, startY, endX, endY)
end
# Set matte (make transparent) in image according to the specified
# colorization rule
def matte(x, y, method)
if ( not PAINT_METHOD_NAMES.has_key?(method.to_i) )
Kernel.raise ArgumentError, "Unknown paint method"
end
primitive "matte #{x},#{y} #{PAINT_METHOD_NAMES[method.to_i]}"
end
# Specify drawing fill and stroke opacities. If the value is a string
# ending with a %, the number will be multiplied by 0.01.
def opacity(opacity)
if (Numeric === opacity)
if (opacity < 0 || opacity > 1.0)
Kernel.raise ArgumentError, "opacity must be >= 0 and <= 1.0"
end
end
primitive "opacity #{opacity}"
end
# Draw using SVG-compatible path drawing commands. Note that the
# primitive requires that the commands be surrounded by quotes or
# apostrophes. Here we simply use apostrophes.
def path(cmds)
primitive "path '" + cmds + "'"
end
# Define a pattern. In the block, call primitive methods to
# draw the pattern. Reference the pattern by using its name
# as the argument to the 'fill' or 'stroke' methods
def pattern(name, x, y, width, height)
begin
push('defs')
push("pattern #{name} #{x} #{y} #{width} #{height}")
push('graphic-context')
yield
ensure
pop('graphic-context')
pop('pattern')
pop('defs')
end
end
# Set point to fill color.
def point(x, y)
primitive "point #{x},#{y}"
end
# Specify the font size in points. Yes, the primitive is "font-size" but
# in other places this value is called the "pointsize". Give it both names.
def pointsize(points)
primitive "font-size #{points}"
end
alias font_size pointsize
# Draw a polygon
def polygon(*points)
if points.length == 0
Kernel.raise ArgumentError, "no points specified"
elsif points.length % 2 != 0
Kernel.raise ArgumentError, "odd number of points specified"
end
primitive "polygon " + points.join(',')
end
# Draw a polyline
def polyline(*points)
if points.length == 0
Kernel.raise ArgumentError, "no points specified"
elsif points.length % 2 != 0
Kernel.raise ArgumentError, "odd number of points specified"
end
primitive "polyline " + points.join(',')
end
# Return to the previously-saved set of whatever
# pop('graphic-context') (the default if no arguments)
# pop('defs')
# pop('gradient')
# pop('pattern')
def pop(*what)
if what.length == 0
primitive "pop graphic-context"
else
# to_s allows a Symbol to be used instead of a String
primitive "pop " + what.map {|w| w.to_s}.join(' ')
end
end
# Push the current set of drawing options. Also you can use
# push('graphic-context') (the default if no arguments)
# push('defs')
# push('gradient')
# push('pattern')
def push(*what)
if what.length == 0
primitive "push graphic-context"
else
# to_s allows a Symbol to be used instead of a String
primitive "push " + what.map {|w| w.to_s}.join(' ')
end
end
# Draw a rectangle
def rectangle(upper_left_x, upper_left_y, lower_right_x, lower_right_y)
primitive "rectangle " + sprintf("%g,%g %g,%g",
upper_left_x, upper_left_y, lower_right_x, lower_right_y)
end
# Specify coordinate space rotation. "angle" is measured in degrees
def rotate(angle)
primitive "rotate #{angle}"
end
# Draw a rectangle with rounded corners
def roundrectangle(center_x, center_y, width, height, corner_width, corner_height)
primitive "roundrectangle " + sprintf("%g,%g,%g,%g,%g,%g",
center_x, center_y, width, height, corner_width, corner_height)
end
# Specify scaling to be applied to coordinate space on subsequent drawing commands.
def scale(x, y)
primitive "scale #{x},#{y}"
end
def skewx(angle)
primitive "skewX #{angle}"
end
def skewy(angle)
primitive "skewY #{angle}"
end
# Specify the object stroke, a color name or pattern name.
def stroke(colorspec)
primitive "stroke #{enquote(colorspec)}"
end
alias stroke_color stroke
alias stroke_pattern stroke
# Specify if stroke should be antialiased or not
def stroke_antialias(bool)
bool = bool ? '1' : '0'
primitive "stroke-antialias #{bool}"
end
# Specify a stroke dash pattern
def stroke_dasharray(*list)
if list.length == 0
primitive "stroke-dasharray none"
else
list.each { |x|
if x <= 0 then
Kernel.raise ArgumentError, "dash array elements must be > 0 (#{x} given)"
end
}
primitive "stroke-dasharray #{list.join(',')}"
end
end
# Specify the initial offset in the dash pattern
def stroke_dashoffset(value=0)
primitive "stroke-dashoffset #{value}"
end
def stroke_linecap(value)
if ( not ["butt", "round", "square"].include?(value.downcase) )
Kernel.raise ArgumentError, "Unknown linecap type: #{value}"
end
primitive "stroke-linecap #{value}"
end
def stroke_linejoin(value)
if ( not ["round", "miter", "bevel"].include?(value.downcase) )
Kernel.raise ArgumentError, "Unknown linejoin type: #{value}"
end
primitive "stroke-linejoin #{value}"
end
def stroke_miterlimit(value)
if (value < 1)
Kernel.raise ArgumentError, "miterlimit must be >= 1"
end
primitive "stroke-miterlimit #{value}"
end
# Specify opacity of stroke drawing color
# (use "xx%" to indicate percentage)
def stroke_opacity(value)
primitive "stroke-opacity #{value}"
end
# Specify stroke (outline) width in pixels.
def stroke_width(pixels)
primitive "stroke-width #{pixels}"
end
# Draw text at position x,y. Add quotes to text that is not already quoted.
def text(x, y, text)
if text.to_s.empty?
Kernel.raise ArgumentError, "missing text argument"
end
if text.length > 2 && /\A(?:\"[^\"]+\"|\'[^\']+\'|\{[^\}]+\})\z/.match(text)
; # text already quoted
elsif !text['\'']
text = '\''+text+'\''
elsif !text['"']
text = '"'+text+'"'
elsif !(text['{'] || text['}'])
text = '{'+text+'}'
else
# escape existing braces, surround with braces
text = '{' + text.gsub(/[}]/) { |b| '\\' + b } + '}'
end
primitive "text #{x},#{y} #{text}"
end
# Specify text alignment relative to a given point
def text_align(alignment)
if ( not ALIGN_TYPE_NAMES.has_key?(alignment.to_i) )
Kernel.raise ArgumentError, "Unknown alignment constant: #{alignment}"
end
primitive "text-align #{ALIGN_TYPE_NAMES[alignment.to_i]}"
end
# SVG-compatible version of text_align
def text_anchor(anchor)
if ( not ANCHOR_TYPE_NAMES.has_key?(anchor.to_i) )
Kernel.raise ArgumentError, "Unknown anchor constant: #{anchor}"
end
primitive "text-anchor #{ANCHOR_TYPE_NAMES[anchor.to_i]}"
end
# Specify if rendered text is to be antialiased.
def text_antialias(boolean)
boolean = boolean ? '1' : '0'
primitive "text-antialias #{boolean}"
end
# Specify color underneath text
def text_undercolor(color)
primitive "text-undercolor #{enquote(color)}"
end
# Specify center of coordinate space to use for subsequent drawing
# commands.
def translate(x, y)
primitive "translate #{x},#{y}"
end
end # class Magick::Draw
# Define IPTC record number:dataset tags for use with Image#get_iptc_dataset
module IPTC
module Envelope
Model_Version = "1:00"
Destination = "1:05"
File_Format = "1:20"
File_Format_Version = "1:22"
Service_Identifier = "1:30"
Envelope_Number = "1:40"
Product_ID = "1:50"
Envelope_Priority = "1:60"
Date_Sent = "1:70"
Time_Sent = "1:80"
Coded_Character_Set = "1:90"
UNO = "1:100"
Unique_Name_of_Object = "1:100"
ARM_Identifier = "1:120"
ARM_Version = "1:122"
end
module Application
Record_Version = "2:00"
Object_Type_Reference = "2:03"
Object_Name = "2:05"
Title = "2:05"
Edit_Status = "2:07"
Editorial_Update = "2:08"
Urgency = "2:10"
Subject_Reference = "2:12"
Category = "2:15"
Supplemental_Category = "2:20"
Fixture_Identifier = "2:22"
Keywords = "2:25"
Content_Location_Code = "2:26"
Content_Location_Name = "2:27"
Release_Date = "2:30"
Release_Time = "2:35"
Expiration_Date = "2:37"
Expiration_Time = "2:35"
Special_Instructions = "2:40"
Action_Advised = "2:42"
Reference_Service = "2:45"
Reference_Date = "2:47"
Reference_Number = "2:50"
Date_Created = "2:55"
Time_Created = "2:60"
Digital_Creation_Date = "2:62"
Digital_Creation_Time = "2:63"
Originating_Program = "2:65"
Program_Version = "2:70"
Object_Cycle = "2:75"
By_Line = "2:80"
Author = "2:80"
By_Line_Title = "2:85"
Author_Position = "2:85"
City = "2:90"
Sub_Location = "2:92"
Province = "2:95"
State = "2:95"
Country_Primary_Location_Code = "2:100"
Country_Primary_Location_Name = "2:101"
Original_Transmission_Reference = "2:103"
Headline = "2:105"
Credit = "2:110"
Source = "2:115"
Copyright_Notice = "2:116"
Contact = "2:118"
Abstract = "2:120"
Caption = "2:120"
Editor = "2:122"
Caption_Writer = "2:122"
Rasterized_Caption = "2:125"
Image_Type = "2:130"
Image_Orientation = "2:131"
Language_Identifier = "2:135"
Audio_Type = "2:150"
Audio_Sampling_Rate = "2:151"
Audio_Sampling_Resolution = "2:152"
Audio_Duration = "2:153"
Audio_Outcue = "2:154"
ObjectData_Preview_File_Format = "2:200"
ObjectData_Preview_File_Format_Version = "2:201"
ObjectData_Preview_Data = "2:202"
end
module Pre_ObjectData_Descriptor
Size_Mode = "7:10"
Max_Subfile_Size = "7:20"
ObjectData_Size_Announced = "7:90"
Maximum_ObjectData_Size = "7:95"
end
module ObjectData
Subfile = "8:10"
end
module Post_ObjectData_Descriptor
Confirmed_ObjectData_Size = "9:10"
end
# Make all constants above immutable
constants.each do |record|
rec = const_get(record)
rec.constants.each { |ds| rec.const_get(ds).freeze }
end
end # module Magick::IPTC
# Ruby-level Magick::Image methods
class Image
include Comparable
alias_method :affinity, :remap
# Provide an alternate version of Draw#annotate, for folks who
# want to find it in this class.
def annotate(draw, width, height, x, y, text, &block)
check_destroyed
draw.annotate(self, width, height, x, y, text, &block)
self
end
# Set the color at x,y
def color_point(x, y, fill)
f = copy
f.pixel_color(x, y, fill)
return f
end
# Set all pixels that have the same color as the pixel at x,y and
# are neighbors to the fill color
def color_floodfill(x, y, fill)
target = pixel_color(x, y)
color_flood_fill(target, fill, x, y, Magick::FloodfillMethod)
end
# Set all pixels that are neighbors of x,y and are not the border color
# to the fill color
def color_fill_to_border(x, y, fill)
color_flood_fill(border_color, fill, x, y, Magick::FillToBorderMethod)
end
# Set all pixels to the fill color. Very similar to Image#erase!
# Accepts either String or Pixel arguments
def color_reset!(fill)
save = background_color
# Change the background color _outside_ the begin block
# so that if this object is frozen the exeception will be
# raised before we have to handle it explicitly.
self.background_color = fill
begin
erase!
ensure
self.background_color = save
end
self
end
# Used by ImageList methods - see ImageList#cur_image
def cur_image
self
end
# Thanks to Russell Norris!
def each_pixel
get_pixels(0, 0, columns, rows).each_with_index do |p, n|
yield(p, n%columns, n/columns)
end
self
end
# Retrieve EXIF data by entry or all. If one or more entry names specified,
# return the values associated with the entries. If no entries specified,
# return all entries and values. The return value is an array of [name,value]
# arrays.
def get_exif_by_entry(*entry)
ary = Array.new
if entry.length == 0
exif_data = self['EXIF:*']
if exif_data
exif_data.split("\n").each { |exif| ary.push(exif.split('=')) }
end
else
get_exif_by_entry() # ensure properties is populated with exif data
entry.each do |name|
rval = self["EXIF:#{name}"]
ary.push([name, rval])
end
end
return ary
end
# Retrieve EXIF data by tag number or all tag/value pairs. The return value is a hash.
def get_exif_by_number(*tag)
hash = Hash.new
if tag.length == 0
exif_data = self['EXIF:!']
if exif_data
exif_data.split("\n").each do |exif|
tag, value = exif.split('=')
tag = tag[1,4].hex
hash[tag] = value
end
end
else
get_exif_by_number() # ensure properties is populated with exif data
tag.each do |num|
rval = self['#%04X' % num.to_i]
hash[num] = rval == 'unknown' ? nil : rval
end
end
return hash
end
# Retrieve IPTC information by record number:dataset tag constant defined in
# Magick::IPTC, above.
def get_iptc_dataset(ds)
self['IPTC:'+ds]
end
# Iterate over IPTC record number:dataset tags, yield for each non-nil dataset
def each_iptc_dataset
Magick::IPTC.constants.each do |record|
rec = Magick::IPTC.const_get(record)
rec.constants.each do |dataset|
data_field = get_iptc_dataset(rec.const_get(dataset))
yield(dataset, data_field) unless data_field.nil?
end
end
nil
end
# Patches problematic change to the order of arguments in 1.11.0.
# Before this release, the order was
# black_point, gamma, white_point
# RMagick 1.11.0 changed this to
# black_point, white_point, gamma
# This fix tries to determine if the arguments are in the old order and
# if so, swaps the gamma and white_point arguments. Then it calls
# level2, which simply accepts the arguments as given.
# Inspect the gamma and white point values and swap them if they
# look like they're in the old order.
# (Thanks to Al Evans for the suggestion.)
def level(black_point=0.0, white_point=nil, gamma=nil)
black_point = Float(black_point)
white_point ||= Magick::QuantumRange - black_point
white_point = Float(white_point)
gamma_arg = gamma
gamma ||= 1.0
gamma = Float(gamma)
if gamma.abs > 10.0 || white_point.abs <= 10.0 || white_point.abs < gamma.abs
gamma, white_point = white_point, gamma
unless gamma_arg
white_point = Magick::QuantumRange - black_point
end
end
return level2(black_point, white_point, gamma)
end
# These four methods are equivalent to the Draw#matte method
# with the "Point", "Replace", "Floodfill", "FilltoBorder", and
# "Replace" arguments, respectively.
# Make the pixel at (x,y) transparent.
def matte_point(x, y)
f = copy
f.opacity = OpaqueOpacity unless f.matte
pixel = f.pixel_color(x,y)
pixel.opacity = TransparentOpacity
f.pixel_color(x, y, pixel)
return f
end
# Make transparent all pixels that are the same color as the
# pixel at (x, y).
def matte_replace(x, y)
f = copy
f.opacity = OpaqueOpacity unless f.matte
target = f.pixel_color(x, y)
f.transparent(target)
end
# Make transparent any pixel that matches the color of the pixel
# at (x,y) and is a neighbor.
def matte_floodfill(x, y)
f = copy
f.opacity = OpaqueOpacity unless f.matte
target = f.pixel_color(x, y)
f.matte_flood_fill(target, TransparentOpacity,
x, y, FloodfillMethod)
end
# Make transparent any neighbor pixel that is not the border color.
def matte_fill_to_border(x, y)
f = copy
f.opacity = Magick::OpaqueOpacity unless f.matte
f.matte_flood_fill(border_color, TransparentOpacity,
x, y, FillToBorderMethod)
end
# Make all pixels transparent.
def matte_reset!
self.opacity = Magick::TransparentOpacity
self
end
# Corresponds to ImageMagick's -resample option
def resample(x_res=72.0, y_res=nil)
y_res ||= x_res
width = x_res * columns / x_resolution + 0.5
height = y_res * rows / y_resolution + 0.5
self.x_resolution = x_res
self.y_resolution = y_res
resize(width, height)
end
# Force an image to exact dimensions without changing the aspect ratio.
# Resize and crop if necessary. (Thanks to Jerett Taylor!)
def resize_to_fill(ncols, nrows=nil, gravity=CenterGravity)
copy.resize_to_fill!(ncols, nrows, gravity)
end
def resize_to_fill!(ncols, nrows=nil, gravity=CenterGravity)
nrows ||= ncols
if ncols != columns || nrows != rows