Class: Image8

Inherits:
Sinatra::Base
  • Object
show all
Defined in:
lib/image8.rb

Instance Method Summary collapse

Instance Method Details

#append_query_string(uri) ⇒ Object



50
51
52
53
54
55
# File 'lib/image8.rb', line 50

def append_query_string uri
  if !request.query_string.empty?
    uri += "?#{request.query_string}"
  end
  uri
end

#doc_id(uri) ⇒ Object



57
58
59
60
61
# File 'lib/image8.rb', line 57

def doc_id uri
  uri = URI.encode(uri)
  uri.gsub! "/", "%2F"
  uri
end

#doc_uri(uri, format = nil, action = nil) ⇒ Object



63
64
65
66
# File 'lib/image8.rb', line 63

def doc_uri uri, format=nil, action=nil
  format = "#{action}/#{format}" if action
  [settings.couchdb, doc_id(uri), format].compact.join("/")
end

#download_original(uri) ⇒ Object



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

def download_original uri
  cache = EM::HttpRequest.new doc_uri(uri, "full")
  request = cache.get

  if request.response_header.status == 200
    puts "Serving original from cache.."
    blob = request.response
    rev  = request.response_header["ETAG"][1..-2]
  else
    puts "Downloading original.."
    original = EM::HttpRequest.new(uri).get
    request = cache.put(
      :head => {'Content-Type' => original.response_header["CONTENT_TYPE"]},
      :body => original.response
    )
    blob = original.response
    rev  = JSON.parse(request.response)["rev"]
  end

  [blob, rev]
end

#format_response(request) ⇒ Object



90
91
92
93
# File 'lib/image8.rb', line 90

def format_response request
  rev  = etag[1..-2]
  [blob, rev]
end

#transform_image(blob, action, format) ⇒ Object



95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
# File 'lib/image8.rb', line 95

def transform_image blob, action, format
  puts "#{action} image.."
  image = Magick::Image.from_blob(blob).first
  case action
  when "resize" then
    image.change_geometry!(format) {|width, height|
      image.resize! width, height
    }
  when "crop" then
    width, height = format.split("x").map {|x| x.to_i}
    image.resize_to_fill! width, height
  when "max" then
    width, height = format.split("x").map {|x| x.to_i}
    actual_width = image.columns
    actual_height = image.rows
    
    if( actual_width > width || actual_height > height )
      image.change_geometry!(format) {|width, height|
        image.resize! width, height
      }
    end
  end
  image
end