Class: ZooniverseData::Helpers::Images::Image

Inherits:
Object
  • Object
show all
Defined in:
lib/zooniverse_data/helpers/images.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(path: nil, raise_exceptions: true) ⇒ Image

Returns a new instance of Image.



13
14
15
16
# File 'lib/zooniverse_data/helpers/images.rb', line 13

def initialize(path: nil, raise_exceptions: true)
  self.path = path
  self.raise_exceptions = raise_exceptions
end

Instance Attribute Details

#pathObject

Returns the value of attribute path.



11
12
13
# File 'lib/zooniverse_data/helpers/images.rb', line 11

def path
  @path
end

#raise_exceptionsObject

Returns the value of attribute raise_exceptions.



11
12
13
# File 'lib/zooniverse_data/helpers/images.rb', line 11

def raise_exceptions
  @raise_exceptions
end

Instance Method Details

#_run_optimization(command) ⇒ Object



69
70
71
72
73
# File 'lib/zooniverse_data/helpers/images.rb', line 69

def _run_optimization(command)
  success = system command
  raise ImageOptimizationError.new('Image optimization failed') unless success
  replace_with_tempfile if @tempfile
end

#infoObject



27
28
29
# File 'lib/zooniverse_data/helpers/images.rb', line 27

def info
  @info ||= FastImage.new(path, raise_on_failure: raise_exceptions)
end

#optimizeObject



31
32
33
34
35
36
37
38
39
40
# File 'lib/zooniverse_data/helpers/images.rb', line 31

def optimize
  tap do
    case type
    when :jpeg
      _run_optimization "jpegtran -copy none -optimize -progressive -outfile '#{ tempfile.path }' '#{ path }'"
    when :png, :bmp, :gif, :tiff
      _run_optimization "optipng #{optipng_options} '#{ path }'"
    end
  end
end

#optipng_optionsObject

-strip all only available after 0.7.0 sourceforge.net/p/optipng/bugs/44/



59
60
61
62
63
64
65
66
67
# File 'lib/zooniverse_data/helpers/images.rb', line 59

def optipng_options
  [ "-o2" , "-quiet" ].tap do |optipng_options|
    if optipng_version = `optipng -v | sed -n 1p`.strip.match(/\s(\d.+):/)
      if optipng_version[1].gsub(".", "").to_i > 70
        optipng_options.unshift("-strip all")
      end
    end
  end.join(" ")
end

#remove_tempfileObject



47
48
49
50
# File 'lib/zooniverse_data/helpers/images.rb', line 47

def remove_tempfile
  tempfile.delete
  @tempfile = nil
end

#replace_with_tempfileObject



52
53
54
55
# File 'lib/zooniverse_data/helpers/images.rb', line 52

def replace_with_tempfile
  `cp '#{ tempfile.path }' '#{ path }'`
  remove_tempfile
end

#sizeObject



18
19
20
21
# File 'lib/zooniverse_data/helpers/images.rb', line 18

def size
  width, height = info.size
  OpenStruct.new width: width, height: height
end

#tempfileObject



42
43
44
45
# File 'lib/zooniverse_data/helpers/images.rb', line 42

def tempfile
  return @tempfile if @tempfile
  @tempfile = Tempfile.new File.basename path
end

#typeObject



23
24
25
# File 'lib/zooniverse_data/helpers/images.rb', line 23

def type
  info.type
end