Class: Axon::Cropper

Inherits:
Object
  • Object
show all
Defined in:
lib/axon/cropper.rb

Overview

An Image Cropper

Axon::Crop allows you to crop images and extract regions.

Example

image_in = Axon::Solid.new(100, 200)
c = Axon::Crop.new(image_in, 50, 75, 10, 20)
c.width  # => 50
c.height # => 75
c.gets   # => String

Example of Cropping Past the Boundaries of the Original Image

image_in = Axon::Solid.new(100, 200)
c = Axon::Crop.new(image_in, 50, 75, 60, 20)
c.width # => 40

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(source, width, height, x_offset = nil, y_offset = nil) ⇒ Cropper

:call-seq:

Cropper.new(image_in, width, height, x_offset = 0, y_offset = 0)

Crops image_in to the size width x height. Optionally, x_offset and y_offset can be used to shift the upper left corner of the cropped area.

If the cropped image extends beyond the boundaries of image_in then the cropped image will be truncated at the boundary.

Raises:

  • (ArgumentError)


35
36
37
38
39
40
41
42
43
44
45
46
47
48
# File 'lib/axon/cropper.rb', line 35

def initialize(source, width, height, x_offset=nil, y_offset=nil)
  x_offset ||= 0
  y_offset ||= 0

  raise ArgumentError if width < 1 || height < 1
  raise ArgumentError if x_offset < 0 || y_offset < 0

  @source = source
  @width = width
  @height = height
  @x_offset = x_offset
  @y_offset = y_offset
  @lineno = 0
end

Instance Attribute Details

#linenoObject (readonly)

The index of the next line that will be fetched by gets, starting at 0.



23
24
25
# File 'lib/axon/cropper.rb', line 23

def lineno
  @lineno
end

Instance Method Details

#componentsObject

Gets the components in the cropped image. Same as the components of the source image.



73
74
75
# File 'lib/axon/cropper.rb', line 73

def components
  @source.components
end

#getsObject

Gets the next scanline from the cropped image.



79
80
81
82
83
84
85
86
87
88
89
90
91
# File 'lib/axon/cropper.rb', line 79

def gets
  return nil if @lineno >= height || width < 1 || height < 1

  while @source.lineno < @y_offset
    break unless @source.gets
  end

  @lineno += 1

  sl_width = width * components
  sl_offset = @x_offset * components
  @source.gets[sl_offset, sl_width]
end

#heightObject

Calculates the height of the cropped image.



52
53
54
55
56
57
58
# File 'lib/axon/cropper.rb', line 52

def height
  if @y_offset + @height > @source.height
    [@source.height - @y_offset, 0].max
  else
    @height
  end
end

#widthObject

Calculates the width of the cropped image.



62
63
64
65
66
67
68
# File 'lib/axon/cropper.rb', line 62

def width
  if @x_offset + @width > @source.width
    [@source.width - @x_offset, 0].max
  else
    @width
  end
end