Class: Photein::Image

Inherits:
MediaFile show all
Defined in:
lib/photein/image.rb

Constant Summary collapse

SUPPORTED_FORMATS =
%w(
  .jpg
  .jpeg
  .dng
  .heic
  .png
).freeze
OPTIMIZATION_FORMAT_MAP =
{
  web: { '.heic' => '.jpg' }
}.freeze
MAX_RES_WEB =

2MP

2097152

Constants inherited from MediaFile

MediaFile::DATE_FORMAT, MediaFile::NORMAL_EXTNAME_MAP

Instance Attribute Summary

Attributes inherited from MediaFile

#path

Instance Method Summary collapse

Methods inherited from MediaFile

for, #import, #initialize

Constructor Details

This class inherits a constructor from Photein::MediaFile

Instance Method Details

#optimize(tempfile:, lib_type:) ⇒ Object



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/photein/image.rb', line 25

def optimize(tempfile:, lib_type:)
  return unless lib_type == :web

  case extname
  when '.jpg', '.heic'
    return false if image.dimensions.reduce(&:*) < MAX_RES_WEB

    Photein.logger.info "optimizing #{path}"
    MiniMagick::Tool::Convert.new do |convert|
      convert << path
      convert.colorspace('sRGB')
      convert.define('jpeg:dct-method=float')
      convert.interlace('JPEG')
      convert.quality('85%')
      convert.resize("#{MAX_RES_WEB}@>")
      convert.sampling_factor('4:2:0')
      convert << tempfile
    end unless Photein::Config.dry_run
  when '.png'
    FileUtils.cp(path, tempfile, noop: Photein::Config.dry_run)
    Photein.logger.info "optimizing #{path}"
    begin
      Optipng.optimize(tempfile, level: 4) unless Photein::Config.dry_run
    rescue Errno::ENOENT
      Photein.logger.error('optipng is required to compress PNG images')
      raise
    end
  end
end