From 4ccf07be8ccf3074163bfcf29460d8cfa2f54eae Mon Sep 17 00:00:00 2001
From: Sam <sam.saffron@gmail.com>
Date: Thu, 22 May 2014 17:34:33 +1000
Subject: [PATCH] Improve resize logic so images end up sharper

---
 app/models/optimized_image.rb | 24 ++++++++++++++++++++----
 1 file changed, 20 insertions(+), 4 deletions(-)

diff --git a/app/models/optimized_image.rb b/app/models/optimized_image.rb
index a3dc6d3c3..592b5e1ad 100644
--- a/app/models/optimized_image.rb
+++ b/app/models/optimized_image.rb
@@ -3,7 +3,7 @@ require "digest/sha1"
 class OptimizedImage < ActiveRecord::Base
   belongs_to :upload
 
-  def self.create_for(upload, width, height)
+  def self.create_for(upload, width, height, opts={})
     return unless width > 0 && height > 0
 
     # do we already have that thumbnail?
@@ -17,8 +17,6 @@ class OptimizedImage < ActiveRecord::Base
 
     # create the thumbnail otherwise
     unless thumbnail
-      @image_sorcery_loaded ||= require "image_sorcery"
-
       external_copy = Discourse.store.download(upload) if Discourse.store.external?
       original_path = if Discourse.store.external?
         external_copy.path
@@ -30,8 +28,9 @@ class OptimizedImage < ActiveRecord::Base
       extension = File.extname(original_path)
       temp_file = Tempfile.new(["discourse-thumbnail", extension])
       temp_path = temp_file.path
+      original_path += "[0]" unless opts[:allow_animation]
 
-      if ImageSorcery.new("#{original_path}[0]").convert(temp_path, resize: "#{width}x#{height}!")
+      if resize(original_path, temp_path, width, height)
         thumbnail = OptimizedImage.create!(
           upload_id: upload.id,
           sha1: Digest::SHA1.file(temp_path).hexdigest,
@@ -68,6 +67,23 @@ class OptimizedImage < ActiveRecord::Base
     end
   end
 
+  protected
+
+  def self.resize(from, to, width, height)
+    instructions = %W{
+      #{from}
+      -resize #{width}x#{height}
+      -background transparent
+      -interpolate Catrom
+      -unsharp 2x0.5+0.7+0
+      -quality 98
+      #{to}
+    }.join(" ")
+
+    `convert #{instructions}`
+    $?.exitstatus == 0
+  end
+
 end
 
 # == Schema Information