Module: LookbookVisualTester::ImageTrimmer

Defined in:
lib/lookbook_visual_tester/services/image_trimmer.rb

Constant Summary collapse

DEFAULT_PADDING =
10
BORDER_COLORS =

Pixels matching any of these colors are considered "empty" border and trimmed.

[
  ChunkyPNG::Color::WHITE,
  ChunkyPNG::Color::TRANSPARENT
].freeze

Class Method Summary collapse

Class Method Details

.border_pixel?(color) ⇒ Boolean

Returns:

  • (Boolean)


55
56
57
# File 'lib/lookbook_visual_tester/services/image_trimmer.rb', line 55

def self.border_pixel?(color)
  BORDER_COLORS.include?(color)
end

.call(path, padding: DEFAULT_PADDING) ⇒ Object



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
# File 'lib/lookbook_visual_tester/services/image_trimmer.rb', line 14

def self.call(path, padding: DEFAULT_PADDING)
  image = ChunkyPNG::Image.from_file(path)

  min_x = image.width
  max_x = -1
  min_y = image.height
  max_y = -1

  image.height.times do |y|
    image.width.times do |x|
      next if border_pixel?(image[x, y])

      min_x = x if x < min_x
      max_x = x if x > max_x
      min_y = y if y < min_y
      max_y = y if y > max_y
    end
  end

  # No content found: keep the original image.
  return path if max_x < min_x

  content_width = max_x - min_x + 1
  content_height = max_y - min_y + 1
  new_width = content_width + (padding * 2)
  new_height = content_height + (padding * 2)

  trimmed = ChunkyPNG::Image.new(new_width, new_height, ChunkyPNG::Color::TRANSPARENT)

  image.height.times do |y|
    image.width.times do |x|
      next if x < min_x || x > max_x || y < min_y || y > max_y

      trimmed[x - min_x + padding, y - min_y + padding] = image[x, y]
    end
  end

  trimmed.save(path)
  path
end