Class: Attachs::Magick::Image

Inherits:
Object
  • Object
show all
Defined in:
lib/attachs/magick/image.rb

Instance Method Summary collapse

Constructor Details

#initialize(source, output = nil) ⇒ Image

Returns a new instance of Image.



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

def initialize(source, output=nil)
  @source = source
  @output = output
end

Instance Method Details

#convert(args) ⇒ Object



10
11
12
13
14
15
16
17
18
19
20
21
# File 'lib/attachs/magick/image.rb', line 10

def convert(args)
  tokens = [convert? ? 'convert' : 'mogrify']
  file_to_tokens tokens
  args_to_tokens args, tokens
  tokens << "\"#{output}\"" if convert?
  success, output = run(tokens)
  if block_given? 
    yield success, output
  else
    success
  end
end

#dimensionsObject



35
36
37
38
39
# File 'lib/attachs/magick/image.rb', line 35

def dimensions
  identify(format: '%wx%h') do |success, output|
    success ? output.chomp.split('x').map(&:to_i) : []
  end
end

#heightObject



45
46
47
# File 'lib/attachs/magick/image.rb', line 45

def height
  dimensions[1]
end

#identify(args) ⇒ Object



23
24
25
26
27
28
29
30
31
32
33
# File 'lib/attachs/magick/image.rb', line 23

def identify(args)
  tokens = ['identify']
  args_to_tokens args, tokens
  file_to_tokens tokens
  success, output = run(tokens)
  if block_given?
    yield success, output
  else
    success
  end
end

#resize_to_fill(max_width, max_height) ⇒ Object



49
50
51
52
53
# File 'lib/attachs/magick/image.rb', line 49

def resize_to_fill(max_width, max_height)
  width, height = dimensions
  scale = [max_width.to_f/width, max_height.to_f/height].max
  convert resize: "#{(scale*width).ceil}x#{(scale*height).ceil}", gravity: 'center', crop: "#{max_width}x#{max_height}+0+0" 
end

#resize_to_fit(max_width, max_height) ⇒ Object



55
56
57
58
59
# File 'lib/attachs/magick/image.rb', line 55

def resize_to_fit(max_width, max_height)
  width, height = dimensions
  scale = [max_width.to_f/width, max_height.to_f/height].reject{ |s| s==0 }.min
  convert resize: "#{(scale*width).ceil}x#{(scale*height).ceil}", gravity: 'center'
end

#widthObject



41
42
43
# File 'lib/attachs/magick/image.rb', line 41

def width
  dimensions[0]
end