Paperclip don't generate styles and original image appears as broken - ruby-on-rails

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

Related

Paperclip not showing image even though URL/images in correct places

Using Paperclip to attach avatars to User profiles for my rails application. I followed the instructions on the paperclip github to initialize and attach to my app.
I have an image in the public/images/medium/missing.png and for both cases (when I upload or when I fallback on the default) I get no image. I've checked my directory and there is an image where it says it is looking but does not grab it. Additionally when I have tried uploading images, I know the image is uploaded correctly because when calling the User in rails console shows all the information properly attached.
I am calling the image in my view like:
<%= image_tag(#blog.user.avatar.url(":medium"), :class => "image-circle avatar") %>
my Paperclip declaration in the User model looks like the following:
has_attached_file :avatar, :styles => { :medium => "300x300>", :thumb => "100x100#"}, :default_url => "/public/images/:style/missing.png"
validates_attachment_content_type :avatar, :content_type => /\Aimage\/.*\Z/
Really not sure what is going on. The route errors that appear when I inspect the improperly loaded image point directly to the image in my local server. And the fact that it can't grab either the missing or the uploaded file also has me at a loss. Any help would be super appreciated!!
And for good measure the output when I examine a user with an uploaded avatar:
avatar_file_name: "11390219_10206114805925816_6595348111261743639_n.j...", avatar_content_type: "image/jpeg", avatar_file_size: 101926, avatar_updated_at: "2015-07-10 18:51:44">
Thanks in advance!
EDIT
This is the URL that is providing the 404 error:
http://localhost:3000/images/medium/missing.png
while in my local directory it goes "root/public/images/medium/missing.png"
not sure how its not grabbing it, unless I am just missing something really obvious somewhere. (i tried hard routing the public in there as well, but to no avail).
EDIT
There is the possibility that you're simply not serving the static assets, add:
config.serve_static_assets = true
to your development.rb
ORIGINAL POST
In you application.rb ( or an environment specific file ), you should have a config.paperclip_defaults = { ... }, here is the link in the docs: https://github.com/thoughtbot/paperclip#defaults
Here is an example one, using fog:
config.paperclip_defaults = {
:storage => :fog,
:fog_credentials => {
:provider => "Local",
:local_root => "#{Rails.root}/public"
},
:fog_directory => "",
:fog_host => "localhost:3000"
}
Do you have something like that in your application? I just tested on an app of mine, and I was able to upload an image, but not to see any without the paperclip_defaults hash. Also, don't forget to restart your app after you update the config files. I hope this helps!
Have you tried killing the quotes around the image style? Around :medium?
<%= image_tag(#blog.user.avatar.url(:medium), :class => "image-circle avatar") %>
As show here in the Paperclip Docs:
https://github.com/thoughtbot/paperclip#show-view
Same problem, solved it by reinstalling imagemagic with brew
Details: In case you're imagemagic, try to update the imagemagic and if it asks you to link it,
Try with this:
brew link --overwrite imagemagick
It worked for me. Hope its helpful

Image in asset pipeline not found

I have seen a number of close problems, but have not been able to find a solution to get solve my problem. I am using Ruby 1.9.3 with Rails 3.2.13.
I am using Prawn to generate a PDF, and I a logo to appear. The logo is found without a problem in the development environment, but fails in the production environment, which is on Heroku.
In my controller I have:
def generate_risk_pdf(risk)
Prawn::Document.new do
image "#{Rails.root}/app/assets/images/logo-print.png", :scale => 0.75 if Rails.env.development?
image "#{ActionController::Base.helpers.asset_path('logo-print.png')}", :scale => 0.75 if Rails.env.production?
move_down 2
formatted_text [{:text => Exercise Australia", :styles => [:bold], :size => 20}]
font_size 6
bounding_box([bounds.right - 150, bounds.bottom], :width => 240, :height => 20) do
text "Copyright: Exercise Australia, #{Date.today.year}"
end
end.render
end
The Heroku logs have
ArgumentError (/assets/logo-print-5b6da7bd4012d953bc1bc749cf934d91.png not found):
app/controllers/single_entries_controller.rb:309:in `block in generate_risk_pdf'
Which corresponds to the line above with Rails.env.production?
If I append the URL to /assets/logo-print-5b6da7bd4012d953bc1bc749cf934d91.png the image file exists.
If I remove that line, it works (minus the logo).
Please note this is not only failing for Prawn, but even when I tried to use an image inline for an email.
Please help, I'm tearing my hair out!
Added: Serving from public works- but it is not my preferred solution.
Try add this to:
rails.root/config/environments/produciton.rb
config.serve_static_assets = true
config.assets.compile = true
A combination of both methods worked for me :
image "#{Rails.root}/app/assets#{ActionController::Base.helpers.asset_path('images/logo-print.png')}"

Rails 3 & Paperclip: "not recognized by the 'identify' command"

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

Rails / Paperclip attaching via command line

I have a bunch of jpeg files in a folder on my server, and I'm attempting to attach them to their corresponding Property instances through a rake task.
property.rb has the following code:
has_attached_file :temp_photo,
:styles => PropertyImage::STYLES,
:url => "/assets/:class/:attachment/:id_partition/:style_:basename.:extension",
:path => "#{Rails.root}/public/assets/:class/:attachment/:id_partition/:style_:basename.:extension"
I use paperclip on other models, and there are no issues whatsoever, but I get a problem when I attempt the following:
p = Property.find(id)
file = File.open(temp_file_path)
p.temp_photo = file
p.save
# => false
file.close
p.errors
# => "/tmp/stream20110524-1126-1cunv0y-0.jpg is not recognized by the 'identify' command."
The file definitely exists, and I've tried changing the permissions. Restarting the server doesn't help. The problem seems to be with using the command line, as the normal form / HTTP approach works fine. This is only a temporary set-up, so I'm looking for a working way to import a batch of files into my rails app paperclip model.
Any suggestions?
path = 'target_file_path'
attach_name = 'temp_photo'
p = Property.find(id)
attach = Paperclip::Attachment.new(attach_name, p, p.class.attachment_definitions[attach_name.to_suym])
file = File.open(path)
attach.assign file
attach.save
file.close

Frequent "No such file or directory" while saving files via Paperclip

I feel like this will end in a facepalm moment but I've been banging on my head on it for too long.
I have a Rails seed.rb file that gets all the files from a specific directory creating a new object for each file and saving the file via Paperclip:
Dir["./**/*.jpg"].each do |f|
...
p = Picture.new
File.open(f, 'r') { |photo_file| p.photo = photo_file }
p.save!
....
end
where photo is the Paperclip-assigned attribute (picture.rb):
has_attached_file :photo,
:styles => { :medium => "500x500>", :thumb => "100x100#" },
:processors => [:rotator]
My problem is after some number of files (some times 50, some times 2) the script exits with the following error:
No such file or directory - /var/folders/oD/oDq1WD11EEaXmfi8VfNvfE+++TM/-Tmp-/stream,22423,0,22423,0
/Users/patgeorge/.rvm/rubies/ruby-1.9.2-head/lib/ruby/1.9.1/fileutils.rb:1407:in `stat'
/Users/patgeorge/.rvm/rubies/ruby-1.9.2-head/lib/ruby/1.9.1/fileutils.rb:1407:in `block in fu_each_src_dest'
/Users/patgeorge/.rvm/rubies/ruby-1.9.2-head/lib/ruby/1.9.1/fileutils.rb:1423:in `fu_each_src_dest0'
/Users/patgeorge/.rvm/rubies/ruby-1.9.2-head/lib/ruby/1.9.1/fileutils.rb:1405:in `fu_each_src_dest'
/Users/patgeorge/.rvm/rubies/ruby-1.9.2-head/lib/ruby/1.9.1/fileutils.rb:504:in `mv'
/Users/patgeorge/.rvm/gems/ruby-1.9.2-head#rails3/bundler/gems/paperclip-61f74de14812cabc026967a2b2c3ca8cbd2eed69-master/lib/paperclip/storage.rb:42:in `block in flush_writes'
I thought maybe I wasn't closing the file but according to the Ruby IO docs using the block from of open will close the file.
Obviously I don't see myself having to run this often so it's not a huge problem. It's just frustrating and confusing.
I'm running Ruby 1.9.2 r28142, Rails 3.0.0.beta4, and Paperclip 2.3.3.
Additional:
Attempting Winfield's suggestion my code block now looks like this:
Dir["./**/*.jpg"].each do |f|
...
File.open(f, 'r') do |photo_file|
p = Picture.new
p.photo = photo_file
p.save!
end
...
end
Still getting the error periodically, though.
Still more info:
I noticed that when I first run my script it's able to do a large amount of files (12 or so). As I continue to run it the number decreases to where I can only do 2 at a time. I'm not sure what I'm doing to make it "reset" and process more. But I imagine that's the key.
This monkey patch solved the issue:
http://github.com/thoughtbot/paperclip/issues/issue/262/
It sure looks to me like you're closing the File handle you opened before you read it out into paperclip.
File.open() with a block opens the file, passes it to the block, and closes it after block execution. This means it's likely closed before you call p.save!
Try doing all of your Photo creation inside your file block:
File.open(f, 'r') {|photo_file| Picture.create!(:photo => photo_file) }

Resources