简体   繁体   English

如何仅使用 Paperclip 为图像文件创建缩略图?

[英]How to create thumbnails only for image files with Paperclip?

I use the following code to create Asset s from the uploaded files:我使用以下代码从上传的文件创建Asset

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, eg my.xlsx , I got the following error:我注意到当我上传非图像文件时,例如my.xlsx ,我收到以下错误:

[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 ?那是因为 Paperclip 试图从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

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')

Change the has_attached_file line to read:has_attached_file行更改为:

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.请注意,如果在处理图像时发生错误,它不会引发错误。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM