Image resizing by using Cloudinary[Ruby]


Cloudinary is one of services providing useful image-based API and CDN. In this article, I would like to introduce Ruby the sample code to resize a image by using the service.

🍄 Installation

Install RubyGem cloudinary. Please add the following RubyGem name and execute bundle install in terminal.

gem 'cloudinary'

😸 Ge API Key

Free member registration from https://cloudinary.com/ and you can get your API key.

🏀 Sample code for resizing image

You can get resized image by the following code:

require 'faraday'

def thumbnail_image(image_url)
tmp_path = _save_image_to_tmp(image_url)
output = ::Cloudinary::Uploader.upload(tmp_path, _cloudinary_auth)
raise "Invalid output! #{output}" if output['public_id'].blank?

_optimized_url(output['public_id'])
end

# @return [String] S3 URL for lambda
private def _save_image_to_tmp(image_url)
content = get_content(image_url)

temp = Tempfile.new.tap do |t|
t.binmode
t.write(_gzip(content))
t.close
end
temp.path
end

private def _get_content(url)
connection = Faraday.new do |conn|
conn.use FaradayMiddleware::FollowRedirects, limit: 5
conn.adapter Faraday.default_adapter
conn.response :encoding
end

response = connection.get url.force_encoding(Encoding::BINARY)
raise NotFoundError, "404 Not Found: #{response.body}" if response.status == 404
raise "Invalid response: #{response.body}" unless response.success?

response.body
end

private def _optimized_url(_public_id)
"http://res.cloudinary.com/USER_NAME/image/upload/w_300,h_300,c_fill,q_auto:eco/#{public_id}.jpg"
end

private def _cloudinary_auth
{
cloud_name: 'xxx',
api_key: 'xxxx',
api_secret: 'xxxx'
}
end

private def _gzip(data)
sio = StringIO.new
gz = Zlib::GzipWriter.new(sio)
gz.write(data)
gz.close
sio.string
end

🗽 References

🖥 Recommended VPS Service

VULTR provides high performance cloud compute environment for you. Vultr has 15 data-centers strategically placed around the globe, you can use a VPS with 512 MB memory for just $ 2.5 / month ($ 0.004 / hour). In addition, Vultr is up to 4 times faster than the competition, so please check it => Check Benchmark Results!!