I'm using paperclip with Rails 3.1. When I add the image, it shows me the original size but doesn't show me thumb or medium sizes:
Here is what I have in my view:
<%= image_tag #image.avatar.url(:thumb) %>
<%= image_tag #image.avatar.url(:medium) %>
image.rb
has_attached_file :avatar, :whiny => false, :styles => { :medium => "300x300>", :thumb => "100x100>" }
UPDATE:
Here is the error I'm getting with :whiny => true
Command :: identify -format %wx%h '/var/folders/54/txjcl9l130j6dq73r37hf2c00000gn/T/stream20111213-9180-1plu1me.png[0]'
[paperclip] An error was received while processing: #
Command :: identify -format %wx%h '/var/folders/54/txjcl9l130j6dq73r37hf2c00000gn/T/stream20111213-9180-1plu1me.png[0]'
[paperclip] An error was received while processing: #
Rendered images/new.html.erb within layouts/application (4.0ms)
First, make sure that Image Magick is installed.
To see if its installed properly, go to a terminal session and type which convert. You should see a path to the executable.
Once that is done, you may need to add the path to your environment.rb file. For example, my convert is located at /usr/local/bin/convert. Now I've seen two different ways of setting your path for paperclip, try one or the other and see what works.
# specifically set the paperclip path
Paperclip.options[:command_path] = '/usr/local/bin'
# set the path in general, might not be necessary
ENV['PATH'] = '/usr/local/bin:' + ENV['PATH']
Related
I having a big issue here. I really tried, but I can't solve this problem by myself, so I hope people can help me here.
Before talk about my problem, I must say I'm using Paperclip and IMGKit in my Project, but I think the problem is with Paperclip.
I create a Rails Task to take snapshots from the home page of some sites. Sometime ago everything is working fine, but now everything goes down. I import my real database from Heroku to localhost (without any images and migrations of paperclip), run the migrations, delete all old files from 'public/system' and run my task again (to take snapshot of all websites).
So, now I have:
The paths and original images are generated, but when I try to load them in View, this just show as a broken image.
Paperclip doesn't generate the path and converted images of :styles.
Sites that don't have image, I can see my default image correctly.
ImageMagick seems to be working, I try convert some images and worked like a charm.
Let's take a look at the code. Assume that I'm running a task that will perform this task to all sites in my database. The sites are called "items" in my architecture.
Development.rb
#config/environments/development.rb
# "which convert" give me this path
Paperclip.options[:command_path] = "/usr/local/bin/"
Item.rb (model)
My task just call "object.save" of every site in the DB, so my code starts on before_save.
has_attached_file :image,
:styles => { :small => "200x147#" },
:convert_options => { :small => "-quality 75 -strip" },
:default_url => '/images/:style/bitcoin-earth.jpg'
before_save :generate_data
def generate_data
self.image = get_image(self.id, self.url_original)
end
# Take snapshot of the website
def get_image(filename, link)
kit = IMGKit.new(link.to_s, :quality => 100, :width => 1024, :height => 768)
file = Tempfile.new(["template_#{filename}", 'png'], 'tmp',
:encoding => 'ascii-8bit')
file.write(kit.to_img(:png))
file.flush
return file
end
View
<%= image_tag store.image.url %>
Gemfile
gem "paperclip"
If I try to run rake paperclip:refresh:missing_styles, the task finish very fast without any error. But if I try to run rake paperclip:refresh CLASS=Item I got:
Image Paperclip::Errors::NotIdentifiedByImageMagickError
And yes, I already search for it and I didn't found a solution for my case.
A little tip?
When I "inspect element" in my project and try to see the source of the item image, I saw:
http://localhost:3000/public/system/items/images/000/000/216/original/template_21620140109-14507-1c0yszzpng?1389305824
But if I go to my project folder, I just see a image called template_21620140109-21209-1yls03opng. Note that doesn't exist any "?1389305824" there. See the image above.
Well, I think that's it. What can be the problem? I really need solve this issue, please, help me :/
[ Edited on Jan 10, 2013 ]
Item.rb (model):
before_save :generate_data
def generate_data
file = File.open(get_image(self.id, self.url_original))
self.image = file
file.close
end
def get_image(filename, link)
kit = IMGKit.new(link.to_s, :quality => 100,
:width => 1024, :height => 768)
file = Tempfile.new(["template_#{filename}", '.png'], 'tmp',
:encoding => 'ascii-8bit')
file.write(kit.to_img(:png))
file.flush
return file
end
Now I don't have any error on console while getting images and saving on DB, but Paperclip still don't generate my :styles. When I go to log/development.log, I can see this error, but I don't know what I can do to solve:
Command :: file -b --mime 'tmp/template_24320140110-17577-80zj1c.png'
Command :: identify -format '%wx%h,%[exif:orientation]' '/tmp/template_24320140110-17577-80zj1c20140110-17577-mqa2q3.png[0]'
[paperclip] An error was received while processing: #<Paperclip::Errors::NotIdentifiedByImageMagickError: Paperclip::Errors::NotIdentifiedByImageMagickError>
I think we're getting closer, please, keep helping me :)
I think your problem is here:
template_21620140109-14507-1c0yszzpng?1389305824 #-> should have .png (not a valid image)
Image
This might not be the problem, but maybe you could streamline your method to exclude the temporary file:
# Take snapshot of the website
def get_image(filename, link)
kit = IMGKit.new(link.to_s, :quality => 100, :width => 1024, :height => 768)
file = kit.to_file("system/temp/template_#{filename}")
return file
end
I think the issue is that ImageMagick is not being passed a "real" file, and consequently you're getting the unrecognized image issues
A few system details:
Mac OS X Lion 10.7.2, Rails 3, Paperclip gem.
ImageMagick 6.7.3-0, binaries installed using MacPorts in /opt/local/bin.
Using WEBrick in development environment.
I'm trying to upload photos that should get resized down into thumbnails. When I do so, the original uploaded file is saved and can be accessed via HTTP correctly. When I try to accessed the thumbnail version, I get this error:
Routing Error
No route matches "[file_URL]"
Before that, when uploading a valid PNG file, I see this error in my WEBrick log:
[paperclip] An error was received while processing: #<Paperclip::NotIdentifiedByImageMagickError: /var/folders/n4/62q22gb52rjd0h13cx_j8vv40000gq/T/stream20111020-24984-17560xt-0.png is not recognized by the 'identify' command.>
Doing which identify outputs:
/opt/local/bin/identify
Calling identify with the path of the uploaded file correctly identifies the file as a PNG file.
I confirmed rails server starts the development environment. I added the following in config/environments/development.rb:
Paperclip.options[:command_path] = "/opt/local/bin"
My Photo model has the following:
class Photo < ActiveRecord::Base
has_attached_file :file, :default_style => :view, :styles => {
:view => { :geometry => '520x390>', :format => 'jpg' },
:preview => { :geometry => '160x120>', :format => 'jpg' } }
validates_attachment_content_type :file,
:content_type => [ 'image/jpeg', 'image/pjpeg', 'image/png' ]
end
My Photos controller:
class PhotosController < ApplicationController
# ...
def create
#photo = Photo.create params[:photo]
end
end
Like I said, I can access the original images in the URL path system/files/:id/original, but the resized versions I want aren't accessible and are not found in the filesystem. WEBrick's log suggest Paperclip can't even have ImageMagick identify the images before resizing them.
Any ideas? Thanks in advance!
This may be a duplicate question, as stated above, but this problem was caused by a recent bug in ImageMagick 6.7.3-0 fixed soon after in 6.7.3-1. MacPorts has also been updated with the new release.
In 6.7.3-0, stating the frame number in the file path (e.g. identify /path/to/file.png[0]) caused ImageMagick to segfault ("Segmentation fault 11"). Paperclip specified the frame number to ensure its processing the first frame or page of an image file.
The new release of ImageMagick solved this problem. The bug was mentioned on MacPorts:
https://trac.macports.org/ticket/31643
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
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 :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.
I've set up paperclip in rails and everything is working hunky-dory (i actually had to google that...:).
I've noticed however that Page Speed tells me I could losslessly compress my thumbnail and large images (the ones that paperclip produces) further. Is there an option I can put into my model which does this? I've noticed that mod_deflate doesn't compress images (I'm using Firefox).
You can add compression to paperclip processing using the paperclip-compression gem.
In your Gemfile:
gem "paperclip-compression", "~> 0.1.1"
(of course run bundle install)
In your model:
has_attached_file :avatar,
:styles => { :medium => "300x300>", :thumb => "100x100>" },
:processors => [:thumbnail, :compression]
"jpegtran works by rearranging the compressed data (DCT coefficients), without ever fully decoding the image. Therefore, its transformations are lossless"
Note: if you are running on heroku, you'll need jpegtran, and optipng binaries added to your application. Here's a good article on running binaries on heroku.
You should do your own testing on various JPEG compression levels but I've noticed that I can bump ImageMagicks quality setting down to 75 and still not see any noticeable difference - with about a 30-40% file size savings.
My model looks like:
has_attached_file :photo,
:styles => {
:"185x138" => {
:geometry => "185x138>"
} },
:convert_options => {
:all => "-auto-orient",
:"185x138" => "-quality 75",
-quality 75 is for ImageMagick. If you're using a different processor you will need to adjust accordingly.
What about FFMPEG or AVCONV?
sudo apt-get install ffmpeg/avconv
= initializer
Paperclip.options[:command_path] = "/usr/bin/" # see `which ffmpeg`
= Modal
after_save :compress_with_ffmpeg
def compress_with_ffmpeg
[:thumb, :original, :medium].each do |type|
img_path = self.avtar.path(type)
Paperclip.run("ffmpeg", " -i #{img_path} #{img_path}")
end
end
I have a problem with the validation of the content type by the Paperclip plug-in:
image.rb (relevant extract)
has_attached_file :photo,
:styles => {:xlarge => "640x512>", :large => "350x280>", :medium => "180x144^",
:thumb => "100x80^", :original => "1280x1280>" },
:convert_options => {:xlarge => "-strip", :large => "-strip",
:medium => "-strip -gravity center -extent 180x144 +repage",
:thumb => "-strip -gravity center -extent 100x80 +repage"},
:default_style => :medium,
:url => "/system/:attachment/:id/:basename_:id_:style.:extension"
validates_attachment_presence :photo
validates_attachment_content_type :photo, :content_type => ['image/jpeg', 'image/png', 'image/gif', 'image/pjpeg', 'image/x-png', 'image/jpeg2000'], :message => 'Uploaded file is not an image'
I'm using nested forms, the image model is the child model of the property model.
During testing the validations of my form I come across some problems. I'm testing validations by uploading a PDF file where the model accepts only images.
output in my form view of: <%= #property.errors.inspect %>
#[#, #message="Uploaded file is not an image">],
"images.photo"=>[#, #message="C:/Users/Michael/AppData/Local/Temp/stream,4272,1.pdf is not recognized by the 'identify' command.">]}>, #base=#>
output in the view of the validation error(s) on the file upload input box:
C:/Users/Michael/AppData/Local/Temp/stream,4272,1.pdf is not recognized by the 'identify' command.
C:/Users/Michael/AppData/Local/Temp/stream,4272,1.pdf is not recognized by the 'identify' command.
C:/Users/Michael/AppData/Local/Temp/stream,4272,1.pdf is not recognized by the 'identify' command.
C:/Users/Michael/AppData/Local/Temp/stream,4272,1.pdf is not recognized by the 'identify' command.
C:/Users/Michael/AppData/Local/Temp/stream,4272,1.pdf is not recognized by the 'identify' command.
2 issues:
issue 1
The input field shows 5 times the same error, that is because I have 5 styles set up in the model. Question is, why does paperclip try to identify (and probably convert the pdf), when you would expect the validation to run first and return already an error before trying to identify and convert? Does Paperclip convert to all the styles before running validations? If yes, is there a way to switch the order of processing, first validation, then styles processing?
issue 2
How can I display the error message of the validation ('Uploaded file is not an image') next to the file upload input box instead of the erros now displayed (5 x the output of the identify command), the latter is of no use to the website user.
Thanks!
I have used
has_attached_file :photo, :whiny => false
and this seems to have helped the error messages. For the error messages, I was using
OBJECT.errors[:photo_content_type]
OBJECT.errors[:photo_file_size]