Method: Imagery::Core#save

Defined in:
lib/imagery.rb

#save(io, id = nil) ⇒ Object

Accepts an ‘IO` object, typically taken from an input.

The second optional ‘id` argument is used when you want to force a new resource, useful in conjunction with cloudfront / high cache scenarios where updating an existing image won’t suffice.

Examples:

# Let's say we're in the context of a Sinatra handler,
# and a file was submitted to params[:file]

post "upload" do
  im = Imagery.new(:avatar, current_user.id, thumb: ["20x20"])
  im.save(params[:file][:tempfile])

  # At this point we have two files, original.jpg and thumb.jpg

  { original: im.url, thumb: im.url(:thumb) }.to_json
end


67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
# File 'lib/imagery.rb', line 67

def save(io, id = nil)
  GM.identify(io) or raise(InvalidImage)

  # We delete the existing object iff:
  # 1. An id was passed
  # 2. We have an existing id already.
  # 3. The id passed is different from the existing id.
  delete if id && self.id && id != self.id

  # Now we can assign the new id passed, with the assurance that the
  # old id has been deleted and won't be used anymore.
  @id = id.to_s if id

  # Ensure that the path to all images is created.
  FileUtils.mkdir_p(root)

  # Write the original filename as binary using the `IO` object's data.
  File.open(root(ext(@original)), "wb") { |file| file.write(io.read) }

  # We resize the original raw image to different sizes which we
  # defined in the constructor. GraphicsMagick is assumed to exist
  # within the machine.
  sizes.each do |size, (resize, extent)|
    GM.convert root(ext(@original)), root(ext(size)), resize, extent
  end
end