Class: Magick::Image

Inherits:
Object
  • Object
show all
Includes:
Comparable
Defined in:
lib/RMagick.rb,
lib/rmagick4j/image.rb

Overview

Ruby-level Magick::Image methods

Defined Under Namespace

Classes: Info, View

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(columns, rows, fill = nil, &info_block) ⇒ Image

Returns a new instance of Image.



168
169
170
171
172
# File 'lib/rmagick4j/image.rb', line 168

def initialize(columns, rows, fill=nil, &info_block)
  info = Info.new(&info_block)
  @image = Magick4J.MagickImage.new(columns, rows, info._info)
  fill.fill(self) if fill.respond_to? :fill
end

Class Method Details

.allocate(*args, &add) ⇒ Object



23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
# File 'lib/rmagick4j/image.rb', line 23

def self.allocate(*args, &add)
  info = Info.new(&add)
  if args.length == 1
    case args[0]
    when String then
      # TODO Respect Dir.getwd
      name = args[0]
      @image = Magick4J.ImageDatabase.createDefault(name, info._info) || Magick4J.MagickImage.new(java.io.File.new(name))
    when Magick4J.MagickImage then
      @image = args[0]
    when Image then
      @image = args[0]._image
    else
      raise ArgumentError, "The argument just can be a String, a MagickImage or an Image instance."
    end
  else
    @image = Magick4J.MagickImage.new(args[0], args[1], info._info)
    if args.length == 3
      args[2].fill(self)
    end
  end
end

.from_blob(blob, &add) ⇒ Object



5
6
7
8
# File 'lib/rmagick4j/image.rb', line 5

def self.from_blob(blob, &add)
  # TODO multiple images in file
  [Image.from_image(Magick4J.MagickImage.from_blob(blob.to_java_bytes), &add)]
end

.from_image(image, &add) ⇒ Object

Raises:

  • (ArgumentError)


16
17
18
19
20
21
# File 'lib/rmagick4j/image.rb', line 16

def self.from_image(image, &add)
  raise ArgumentError, 'First parameter must be a MagickImage instance.' unless image.is_a? Magick4J.MagickImage
  magick_image = Image.new(image.getWidth(), image.getHeight(), &add)
  magick_image._image = image
  magick_image
end

.read(file, &add) ⇒ Object



10
11
12
13
14
# File 'lib/rmagick4j/image.rb', line 10

def self.read(file, &add)
  info = Info.new(&add)
  image = Magick4J.ImageDatabase.createDefault(file.to_s, info._info) || Magick4J.MagickImage.new(java.io.File.new(file.to_s))
  [Image.from_image(image,&add)]
end

Instance Method Details

#_imageObject



152
153
154
# File 'lib/rmagick4j/image.rb', line 152

def _image
  @image
end

#_image=(new_image) ⇒ Object



156
157
158
# File 'lib/rmagick4j/image.rb', line 156

def _image=(new_image)
  @image = new_image
end

#_infoObject



160
161
162
# File 'lib/rmagick4j/image.rb', line 160

def _info
  @info
end

#_info=(new_info) ⇒ Object



164
165
166
# File 'lib/rmagick4j/image.rb', line 164

def _info=(new_info)
  @info = new_info
end

#annotate(draw, width, height, x, y, text, &block) ⇒ Object

Provide an alternate version of Draw#annotate, for folks who want to find it in this class.



739
740
741
742
743
# File 'lib/RMagick.rb', line 739

def annotate(draw, width, height, x, y, text, &block)
  check_destroyed
  draw.annotate(self, width, height, x, y, text, &block)
  self
end

#background_colorObject



46
47
48
# File 'lib/rmagick4j/image.rb', line 46

def background_color
  @image.getBackgroundColor
end

#background_color=(value) ⇒ Object

Raises:

  • (TypeError)


50
51
52
53
54
# File 'lib/rmagick4j/image.rb', line 50

def background_color=(value)
  raise TypeError, "argument must be color name or pixel (#{value.class} given)" unless value.is_a?(String) || value.is_a?(Pixel)
  value = Pixel.from_color(value) if value.is_a?(String)
  @image.setBackgroundColor(value)
end

#blur_image(radius = 0.0, sigma = 1.0) ⇒ Object



56
57
58
59
# File 'lib/rmagick4j/image.rb', line 56

def blur_image(radius=0.0, sigma=1.0)
  # Swap order on purpose. I wanted them the other way around in Magick4J.
  Image.from_image(@image.blurred(sigma, radius))
end

#change_geometry(geometry) {|geometry.calculate_width(self._image), geometry.calculate_height(self._image), _self| ... } ⇒ Object

Yields:

  • (geometry.calculate_width(self._image), geometry.calculate_height(self._image), _self)

Yield Parameters:

  • _self (Magick::Image)

    the object that the method was called on



61
62
63
64
65
66
67
68
69
70
71
72
73
# File 'lib/rmagick4j/image.rb', line 61

def change_geometry(geometry)
  geometry = Geometry.from_s(geometry.to_s) unless geometry.is_a? Geometry
  index = if geometry.flag.nil?
            0
          else
            geometry.flag._val
          end
  geometry = JGeometries[index].new( geometry.width, geometry.height,
                                     geometry.x, geometry.y)
  yield geometry.calculate_width(self._image),
        geometry.calculate_height(self._image),
        self
end

#color_fill_to_border(x, y, fill) ⇒ Object

Set all pixels that are neighbors of x,y and are not the border color to the fill color



761
762
763
# File 'lib/RMagick.rb', line 761

def color_fill_to_border(x, y, fill)
    color_flood_fill(border_color, fill, x, y, Magick::FillToBorderMethod)
end

#color_floodfill(x, y, fill) ⇒ Object

Set all pixels that have the same color as the pixel at x,y and are neighbors to the fill color



754
755
756
757
# File 'lib/RMagick.rb', line 754

def color_floodfill(x, y, fill)
    target = pixel_color(x, y)
    color_flood_fill(target, fill, x, y, Magick::FloodfillMethod)
end

#color_point(x, y, fill) ⇒ Object

Set the color at x,y



746
747
748
749
750
# File 'lib/RMagick.rb', line 746

def color_point(x, y, fill)
    f = copy
    f.pixel_color(x, y, fill)
    return f
end

#color_reset!(fill) ⇒ Object

Set all pixels to the fill color. Very similar to Image#erase! Accepts either String or Pixel arguments



767
768
769
770
771
772
773
774
775
776
777
778
779
# File 'lib/RMagick.rb', line 767

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

#columnsObject



75
76
77
# File 'lib/rmagick4j/image.rb', line 75

def columns
  @image.getWidth
end

#composite(*args) ⇒ Object



79
80
81
82
83
84
# File 'lib/rmagick4j/image.rb', line 79

def composite(*args)
  # image, x, y, composite_op
  args[0] = args[0]._image
  args.map! {|arg| arg.is_a?(Enum) ? arg._val : arg}
  Image.from_image(@image.composited(*args))
end

#copyObject



86
87
88
# File 'lib/rmagick4j/image.rb', line 86

def copy
  Image.from_image(@image.clone)
end

#crop(*args) ⇒ Object



90
91
92
# File 'lib/rmagick4j/image.rb', line 90

def crop(*args)
  copy.crop!(*args)
end

#crop!(*args) ⇒ Object



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
# File 'lib/rmagick4j/image.rb', line 94

def crop!(*args)
  # gravity, x, y, width, height, reset_offset
  # Defaults.
  gravity = nil
  x = y = -1
  reset_offset = false
  # Find available args.
  if args.first.is_a? GravityType
    gravity = args.shift._val
  end
  if [FalseClass, TrueClass].member? args.last.class
    reset = args.pop
  end
  if args.length == 4
    x, y = args[0..1]
  end
  width, height = args[-2..-1]
  # Call Java.
  # TODO Why wouldn't we reset offset information? Do we need to use that?
  @image =  unless gravity.nil?
              if x == -1 || y == -1
                @image.crop(gravity, width, height)
              else
                @image.crop(gravity, x, y, width, height)
              end
            else
              @image.crop(x,y,width,height)
            end
  self
end

#cur_imageObject

Used by ImageList methods - see ImageList#cur_image



782
783
784
# File 'lib/RMagick.rb', line 782

def cur_image
    self
end

#displayObject



125
126
127
128
# File 'lib/rmagick4j/image.rb', line 125

def display
  @image.display
  self
end

#each_iptc_datasetObject

Iterate over IPTC record number:dataset tags, yield for each non-nil dataset



844
845
846
847
848
849
850
851
852
853
# File 'lib/RMagick.rb', line 844

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

#each_pixelObject

Thanks to Russell Norris!



787
788
789
790
791
792
# File 'lib/RMagick.rb', line 787

def each_pixel
  get_pixels(0, 0, columns, rows).each_with_index do |p, n|
    yield(p, n%columns, n/columns)
  end
  self
end

#erase!Object



130
131
132
# File 'lib/rmagick4j/image.rb', line 130

def erase!
  @image.erase
end

#flipObject



143
144
145
# File 'lib/rmagick4j/image.rb', line 143

def flip
  copy.flip
end

#flip!Object



147
148
149
150
# File 'lib/rmagick4j/image.rb', line 147

def flip!
  @image.flip
  self
end

#formatObject



134
135
136
# File 'lib/rmagick4j/image.rb', line 134

def format
  @image.getFormat
end

#format=(format) ⇒ Object



138
139
140
141
# File 'lib/rmagick4j/image.rb', line 138

def format= format
  @image.setFormat(format)
  self
end

#get_exif_by_entry(*entry) ⇒ Object

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.



798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
# File 'lib/RMagick.rb', line 798

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

#get_exif_by_number(*tag) ⇒ Object

Retrieve EXIF data by tag number or all tag/value pairs. The return value is a hash.



816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
# File 'lib/RMagick.rb', line 816

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

#get_iptc_dataset(ds) ⇒ Object

Retrieve IPTC information by record number:dataset tag constant defined in Magick::IPTC, above.



839
840
841
# File 'lib/RMagick.rb', line 839

def get_iptc_dataset(ds)
    self['IPTC:'+ds]
end

#level(black_point = 0.0, white_point = nil, gamma = nil) ⇒ Object

(Thanks to Al Evans for the suggestion.)



868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
# File 'lib/RMagick.rb', line 868

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

#matte=(matte) ⇒ Object



174
175
176
# File 'lib/rmagick4j/image.rb', line 174

def matte= matte
  @image.setMatte(matte)
end

#matte_fill_to_border(x, y) ⇒ Object

Make transparent any neighbor pixel that is not the border color.



922
923
924
925
926
927
# File 'lib/RMagick.rb', line 922

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

#matte_floodfill(x, y) ⇒ Object

Make transparent any pixel that matches the color of the pixel at (x,y) and is a neighbor.



913
914
915
916
917
918
919
# File 'lib/RMagick.rb', line 913

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

#matte_point(x, y) ⇒ Object

Make the pixel at (x,y) transparent.



893
894
895
896
897
898
899
900
# File 'lib/RMagick.rb', line 893

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

#matte_replace(x, y) ⇒ Object

Make transparent all pixels that are the same color as the pixel at (x, y).



904
905
906
907
908
909
# File 'lib/RMagick.rb', line 904

def matte_replace(x, y)
    f = copy
    f.opacity = OpaqueOpacity unless f.matte
    target = f.pixel_color(x, y)
    f.transparent(target)
end

#matte_reset!Object

Make all pixels transparent.



930
931
932
933
# File 'lib/RMagick.rb', line 930

def matte_reset!
    self.opacity = Magick::TransparentOpacity
    self
end

#quantize(number_colors = 256, colorspace = RGBColorspace, dither = true, tree_depth = 0, measure_error = false) ⇒ Object



178
179
180
# File 'lib/rmagick4j/image.rb', line 178

def quantize(number_colors=256, colorspace=RGBColorspace, dither=true, tree_depth=0, measure_error=false)
  Image.from_image(@image.quantized(number_colors, colorspace._val, dither, tree_depth, measure_error))
end

#raise(width = 6, height = 6, raise = true) ⇒ Object



182
183
184
# File 'lib/rmagick4j/image.rb', line 182

def raise(width=6, height=6, raise=true)
  Image.from_image(@image.raised(width, height, raise))
end

#resample(x_res = 72.0, y_res = nil) ⇒ Object

Corresponds to ImageMagick’s -resample option



936
937
938
939
940
941
942
943
# File 'lib/RMagick.rb', line 936

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

#resize(*args) ⇒ Object



186
187
188
# File 'lib/rmagick4j/image.rb', line 186

def resize(*args)
  copy.resize!(*args)
end

#resize!(*args) ⇒ Object



190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
# File 'lib/rmagick4j/image.rb', line 190

def resize!(*args)
  @image =  if args.length == 1
              @image.resized(args[0])
            elsif args.length == 2 # It must be 4 nor 2, but two of them are not yet implemented
              # TODO  Implement the other two arguments.
              # arg[0] --> new_width
              # arg[1] --> new_height
              # arg[2] --> filter=LanczosFilter
              # arg[3] --> support=1.0
              @image.resized(args[0],args[1])
            else
              Kernel.raise ArgumentError, "wrong number of parameters(#{args.length} for 1 or 4)"
            end
  self
end

#resize_to_fill(ncols, nrows = nil, gravity = CenterGravity) ⇒ Object Also known as: crop_resized

Force an image to exact dimensions without changing the aspect ratio. Resize and crop if necessary. (Thanks to Jerett Taylor!)



947
948
949
# File 'lib/RMagick.rb', line 947

def resize_to_fill(ncols, nrows=nil, gravity=CenterGravity)
    copy.resize_to_fill!(ncols, nrows, gravity)
end

#resize_to_fill!(ncols, nrows = nil, gravity = CenterGravity) ⇒ Object Also known as: crop_resized!



951
952
953
954
955
956
957
958
959
# File 'lib/RMagick.rb', line 951

def resize_to_fill!(ncols, nrows=nil, gravity=CenterGravity)
    nrows ||= ncols
    if ncols != columns || nrows != rows
        scale = [ncols/columns.to_f, nrows/rows.to_f].max
        resize!(scale*columns+0.5, scale*rows+0.5)
    end
    crop!(gravity, ncols, nrows, true) if ncols != columns || nrows != rows
    self
end

#resize_to_fit(cols, rows = nil) ⇒ Object

Convenience method to resize retaining the aspect ratio. (Thanks to Robert Manni!)



967
968
969
970
971
972
# File 'lib/RMagick.rb', line 967

def resize_to_fit(cols, rows=nil)
    rows ||= cols
    change_geometry(Geometry.new(cols, rows)) do |ncols, nrows|
        resize(ncols, nrows)
    end
end

#resize_to_fit!(cols, rows = nil) ⇒ Object



974
975
976
977
978
979
# File 'lib/RMagick.rb', line 974

def resize_to_fit!(cols, rows=nil)
    rows ||= cols
    change_geometry(Geometry.new(cols, rows)) do |ncols, nrows|
        resize!(ncols, nrows)
    end
end

#rotate(amount, qualifier = nil) ⇒ Object



206
207
208
# File 'lib/rmagick4j/image.rb', line 206

def rotate(amount, qualifier=nil)
  copy.rotate!(amount,qualifier)
end

#rotate!(amount, qualifier = nil) ⇒ Object



210
211
212
213
214
215
216
217
218
219
220
221
222
223
# File 'lib/rmagick4j/image.rb', line 210

def rotate!(amount, qualifier=nil)
  if qualifier == '<' && columns < rows
    @image.rotate(amount)
    self
  elsif qualifier == '>' && columns > rows
    @image.rotate(amount)
    self
  elsif qualifier.nil?
    @image.rotate(amount)
    self
  else
    nil
  end
end

#rowsObject



225
226
227
# File 'lib/rmagick4j/image.rb', line 225

def rows
  @image.getHeight
end

#store_pixels(x, y, columns, rows, pixels) ⇒ Object

Raises:

  • (IndexError)


229
230
231
232
233
# File 'lib/rmagick4j/image.rb', line 229

def store_pixels(x, y, columns, rows, pixels)
  ria_size = columns*rows
  raise IndexError, "not enough elements in array - expecting #{ria_size}, got #{pixels.size}" if pixels.size < ria_size
  @image.storePixels(x,y,columns,rows,pixels.to_java)
end

#texture_fill_to_border(x, y, texture) ⇒ Object

Replace neighboring pixels to border color with texture pixels



988
989
990
# File 'lib/RMagick.rb', line 988

def texture_fill_to_border(x, y, texture)
    texture_flood_fill(border_color, texture, x, y, FillToBorderMethod)
end

#texture_floodfill(x, y, texture) ⇒ Object

Replace matching neighboring pixels with texture pixels



982
983
984
985
# File 'lib/RMagick.rb', line 982

def texture_floodfill(x, y, texture)
    target = pixel_color(x, y)
    texture_flood_fill(target, texture, x, y, FloodfillMethod)
end

#to_blob(&add) ⇒ Object



235
236
237
238
239
# File 'lib/rmagick4j/image.rb', line 235

def to_blob(&add)
  info = Info.new(&add)
  @image.setFormat(info.format) if info.format
  String.from_java_bytes(@image.toBlob)
end

#view(x, y, width, height) ⇒ Object

Construct a view. If a block is present, yield and pass the view object, otherwise return the view object.



994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
# File 'lib/RMagick.rb', line 994

def view(x, y, width, height)
    view = View.new(self, x, y, width, height)

    if block_given?
        begin
            yield(view)
        ensure
            view.sync
        end
        return nil
    else
        return view
    end
end

#watermark(mark, lightness = 1.0, saturation = 1.0, gravity = nil, x_offset = 0, y_offset = 0) ⇒ Object



241
242
243
244
245
246
247
248
249
250
# File 'lib/rmagick4j/image.rb', line 241

def watermark(mark, lightness=1.0, saturation=1.0, gravity=nil, x_offset=0, y_offset=0)
  if gravity.is_a? Numeric
    # gravity is technically an optional argument in the middle.
    gravity = nil
    y_offset = x_offset
    x_offset = gravity
  end
  # TODO Perform watermark.
  self
end

#write(file, &add) ⇒ Object



252
253
254
255
256
257
258
# File 'lib/rmagick4j/image.rb', line 252

def write(file, &add)
  # TODO I'm having trouble finding out how this info is used, so I'll skip using it for now.
  info = Info.new(&add)
  # TODO Resolve pwd as needed
  @image.write(file)
  self
end