Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Paperclip: How to resize an image only if it is big enough?

I use Paperclip to resize pictures like this:

class Asset < ActiveRecord::Base
  has_attached_file :asset, :styles => { :thumb => "80x80#", 
                                         :medium => "1280x800>" }, ...

When the size of the original picture is 32x32:

  1. The resulting medium picture is of the same size (i.e. 32x32), but the file is a bit different and the picture looks a bit changed. Why is that ?

  2. The resulting thumb size is 80x80 (it looks stretched to fit this size). How could I avoid resizing the picture when it's too small. Assume that original picture's dimensions are in the width and height variables.

like image 410
Misha Moroshko Avatar asked Jul 18 '11 07:07

Misha Moroshko


1 Answers

(1) Is probably because Paperclip is decoding a JPEG and then writing/encoding a new JPEG. JPEG is a lossy format so each encoding degrades the image. You could use the convert_options to adjust the JPEG quality but you'll probably have to accept some degradation in your JPEGs.

(2) is because Paperclip is doing as it's told. Paperclip uses ImageMagick to do the heavy lifting and the style dimensions are just ImageMagick geometry strings with one modification:

Paperclip also adds the “#” option (e.g. “50x50#”), which will resize the image to fit maximally inside the dimensions and then crop the rest off (weighted at the center).

Your :thumb style uses "#" so you're telling Paperclip that you want a 80x80 image even if the image has to be scaled and cropped to get there. You can drop the "#" from the dimensions string and, if desired or appropriate, add one of the the other modifiers.

like image 192
mu is too short Avatar answered Oct 22 '22 11:10

mu is too short