Skip to content

Simple Smusher

I wrote a post on compressing images with TinyPNG, but that 500 image limit ran out fast!  So I decided to see if I could put together my own image optimization service.

After a little digging I found the image_optim gem.  It’s very nice and straightforward, and includes image_optim_pack gem which installed all the compression libraries as well – making for a very hassle free set-up.  After getting those installed and setting up my rails project, it really came down to a simple interface with one controller and view.


require 'open-uri'
require 'image_optim'
require 'fileutils'
class WelcomeController < ApplicationController
  def index
      select{|f| File.mtime(f) < ( - (60*120)) }.
      each{|f| File.delete(f) }
    image = params[:i]
    extension = File.extname(image)
    acceptable_extensions = [".jpg", ".gif", ".png"]
    return @json = "{\"error\":\"only jpg, png, and gif can be resized\"}" if !acceptable_extensions.include?( extension.downcase )
    value = ""; 8.times{value  << (65 + rand(25)).chr}
    tmp_image = "public/tmp/#{value}#{extension}"
    open(tmp_image, 'wb') do |file|
      file << open(image).read
    before_filesize = (File.size(tmp_image) * 0.001).floor
    image_optim =
    image_optim = => false)
    image_optim = => 10)
    after_filesize = (File.size(tmp_image) * 0.001).floor
    tmp_image = "{value}#{extension}"
    @json = "[{\"dest\":\"#{tmp_image}\",\"src_size\":#{before_filesize},\"dest_size\":#{after_filesize}}]"


<%= raw @json %>

I’m including open-uri to download the image to be compressed, image_optim to do the compressing, and fileutils to check the file size.

  1. I start with the Dir.glob to first delete any temporary images that are over 120 hours old.
  2. Then I grab the image from the url provided with the i param, and make sure it has the right extention
  3. Then generate a random string and create the temporary filename and save the image there
  4. Then I optimize the image and save over it
  5. Then I just write out the JSON I want by hand – I wrote it to resemble’s syntax

You will need to change “” to your actual domain here, looking back I should have done that programmatically – but it’s not a big deal.

I have to whole project available on git hub for download.

Published inRoRScripting

Be First to Comment

Leave a Reply

Your email address will not be published. Required fields are marked *