Class: FaceCropper::FaceBox

Inherits:
Object
  • Object
show all
Defined in:
lib/face_cropper/face_box.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(top:, left:, height:, width:, margin: 0) ⇒ FaceBox

Returns a new instance of FaceBox.



7
8
9
10
11
12
13
# File 'lib/face_cropper/face_box.rb', line 7

def initialize(top: , left: , height: , width: , margin: 0)
  @top    = top
  @left   = left
  @height = height
  @width  = width
  @margin = margin
end

Instance Attribute Details

#heightObject (readonly)

Returns the value of attribute height.



5
6
7
# File 'lib/face_cropper/face_box.rb', line 5

def height
  @height
end

#leftObject (readonly)

Returns the value of attribute left.



5
6
7
# File 'lib/face_cropper/face_box.rb', line 5

def left
  @left
end

#topObject (readonly)

Returns the value of attribute top.



5
6
7
# File 'lib/face_cropper/face_box.rb', line 5

def top
  @top
end

#widthObject (readonly)

Returns the value of attribute width.



5
6
7
# File 'lib/face_cropper/face_box.rb', line 5

def width
  @width
end

Instance Method Details

#calculate_position(image_width:, image_height:) ⇒ Object



28
29
30
31
32
33
34
35
# File 'lib/face_cropper/face_box.rb', line 28

def calculate_position(image_width: , image_height:)
  {
    width:  (@width  * image_width).to_i  + @margin,
    height: (@height * image.height).to_i + @margin,
    x:      [(@top   * image.height).to_i - @margin, 0].min,
    y:      [(@left  * image.width).to_i  - @margin, 0].min
  }
end

#crop_face!(image_path) ⇒ Object



15
16
17
18
19
20
21
22
23
24
25
26
# File 'lib/face_cropper/face_box.rb', line 15

def crop_face!(image_path)
  image = MiniMagick::Image.open(image_path)
  position = calculate_position(image_width: image.width, image_height: image.height)

  crop_params = "#{position[:width]}x#{position[:height]}+#{position[:y]}+#{position[:x]}"

  image.crop(crop_params)
  crop_file = "#{crop_params}_#{@image_key}"
  image.write(crop_file)

  crop_file
end