Misha Moroshko
Misha Moroshko

Reputation: 171439

How to create thumbnails only for image files with Paperclip?

I use the following code to create Assets from the uploaded files:

def upload
  uploader = User.find_by_id(params[:uploader_id])
  params[:assets].each do |file|
    new_asset = uploader.assets.build(:asset => file) # Here the error appears
    new_asset.save
  end
  ...
end

I noticed that when I upload non-image files, e.g. my.xlsx, I got the following error:

[paperclip] identify -format %wx%h "C:/temp/stream20110628-460-3vqjnd.xlsx[0]" 2>NUL
[paperclip] An error was received while processing: 
#<Paperclip::NotIdentifiedByImageMagickError: C:/temp/stream20110628-460-3vqjnd.xlsx is
not recognized by the 'identify' command.>

(For image files everything works fine: a thumbnail is created, and there is no error.)

Is that because Paperclip tries to create a thumbnail from my.xlsx ?

What configuration will create thumbnails only for image files ?

Here is some relevant code:

class Asset < ActiveRecord::Base
  belongs_to :uploader, :class_name => "User"
  has_attached_file :asset, :styles => { :thumb => "80x80#" }
end

Upvotes: 2

Views: 1802

Answers (2)

Robin Fisher
Robin Fisher

Reputation: 1454

Change the has_attached_file line to read:

has_attached_file :asset, :styles => { :thumb=> "80x80#" }, :whiny_thumbnails => false

This will prevent it from raising an error when thumbnails are not created. Note though that it won't raise errors if one occurs when processing an image though.

Upvotes: 0

Misha Moroshko
Misha Moroshko

Reputation: 171439

I used the following nice solution:

before_post_process :image?

def image?
  (asset_content_type =~ SUPPORTED_IMAGES_REGEX).present?
end

where:

SUPPORTED_IMAGE_FORMATS = ["image/jpeg", "image/png", "image/gif", "image/bmp"]
SUPPORTED_IMAGES_REGEX = Regexp.new('\A(' + SUPPORTED_IMAGE_FORMATS.join('|') + ')\Z')

Upvotes: 8

Related Questions