From 61d85206ee0a5b88897ee694c7612ca8eed0aa1c Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?R=C3=A9gis=20Hanol?= <regis@hanol.fr>
Date: Fri, 29 May 2015 15:57:24 +0200
Subject: [PATCH] FIX: optimize uploaded images using lossy but very fast
 compression

---
 .image_optim.yml     |  8 ++++++++
 app/models/upload.rb | 22 ++++++++++++++--------
 2 files changed, 22 insertions(+), 8 deletions(-)
 create mode 100644 .image_optim.yml

diff --git a/.image_optim.yml b/.image_optim.yml
new file mode 100644
index 000000000..a729cbd9c
--- /dev/null
+++ b/.image_optim.yml
@@ -0,0 +1,8 @@
+skip_missing_workers: true
+allow_lossy: true
+advpng: false
+optipng: false
+pngcrush: false
+pngout: false
+pngquant:
+  quality: !ruby/range 10..90
diff --git a/app/models/upload.rb b/app/models/upload.rb
index eb967cf9d..22b47682a 100644
--- a/app/models/upload.rb
+++ b/app/models/upload.rb
@@ -74,18 +74,24 @@ class Upload < ActiveRecord::Base
       upload.url               = ""
       upload.origin            = options[:origin][0...1000] if options[:origin]
 
-      # deal with width & height for images
-      upload = resize_image(filename, file, upload) if FileHelper.is_image?(filename)
+      if FileHelper.is_image?(filename)
+        # deal with width & height for images
+        upload = resize_image(filename, file, upload)
+        # optimize image
+        ImageOptim.new.optimize_image!(file.path) rescue nil
+      end
 
       return upload unless upload.save
 
       # store the file and update its url
-      url = Discourse.store.store_upload(file, upload, options[:content_type])
-      if url.present?
-        upload.url = url
-        upload.save
-      else
-        upload.errors.add(:url, I18n.t("upload.store_failure", { upload_id: upload.id, user_id: user_id }))
+      File.open(file.path) do |f|
+        url = Discourse.store.store_upload(f, upload, options[:content_type])
+        if url.present?
+          upload.url = url
+          upload.save
+        else
+          upload.errors.add(:url, I18n.t("upload.store_failure", { upload_id: upload.id, user_id: user_id }))
+        end
       end
 
       # return the uploaded file