Paperclip for both images and Videos
Looks like the issue is that ImageMagick
is trying to transcode the video, which it cannot.
The way to handle transcoding of videos within Paperclip
is to use the paperclip-av-transcoder
gem (formerly paperclip-ffmpeg
). I only have experience with the latter:
#app/models/attachment.rb
class Attachment < ActiveRecord::Base
has_attached_file :url, :s3_protocol => :https ,
styles: lambda { |a| a.instance.is_image? ? medium: "300x300>", thumb: "100x100>", big: "1200x1200>", normal: "600x600>" } : {:thumb => { :geometry => "100x100#", :format => 'jpg', :time => 10}, :medium => { :geometry => "300x300#", :format => 'jpg', :time => 10}}}, processors: [:transcoder]
validates_attachment :url,
content_type: ['video/mp4'],
message: "Sorry, right now we only support MP4 video",
if: :is_video?
validates_attachment :url,
content_type: ['image/png', 'image/jpeg', 'image/jpg', 'image/gif'],
message: "Different error message",
if: :is_image?
private
def is_video?
url.instance.attachment_content_type =~ %r(video)
end
def is_image?
url.instance.attachment_content_type =~ %r(image)
end
end
Our old code & ref
How can I restrict Paperclip to only accept images?
Paperclip has validation methods like validates_attachment_presence
, validates_attachment_content_type
, and validates_attachment_size
.
So all you need to do is pass mime types of images you'd like to have as attachments:
validates_attachment_content_type 'image/png', 'image/jpg'
Paperclip post process - How to compress image using jpegoptim/optpng
Since there's no other answers, here is how I do it in my project and it seems it's being working ok for several months.
class AttachedImage < ActiveRecord::Base
belongs_to :attachable, :polymorphic => true
validates_attachment_presence :image
validates_attachment_content_type :image, :content_type=>['image/jpeg', 'image/png', 'image/gif']
has_attached_file :image,
:styles => {:thumb => '50x50>', :preview => '270x270>' },
# :processors => [:image_compressor],
:url => "/system/:class/:attachment/:id/:basename_:style.:extension",
:path => ":rails_root/public/system/:class/:attachment/:id/:basename_:style.:extension"
after_post_process :compress
private
def compress
current_format = File.extname(image.queued_for_write[:original].path)
image.queued_for_write.each do |key, file|
reg_jpegoptim = /(jpg|jpeg|jfif)/i
reg_optipng = /(png|bmp|gif|pnm|tiff)/i
logger.info("Processing compression: key: #{key} - file: #{file.path} - ext: #{current_format}")
if current_format =~ reg_jpegoptim
compress_with_jpegoptim(file)
elsif current_format =~ reg_optipng
compress_with_optpng(file)
else
logger.info("File: #{file.path} is not compressed!")
end
end
end
def compress_with_jpegoptim(file)
current_size = File.size(file.path)
Paperclip.run("jpegoptim", "-o --strip-all #{file.path}")
compressed_size = File.size(file.path)
compressed_ratio = (current_size - compressed_size) / current_size.to_f
logger.debug("#{current_size} - #{compressed_size} - #{compressed_ratio}")
logger.debug("JPEG family compressed, compressed: #{ '%.2f' % (compressed_ratio * 100) }%")
end
def compress_with_optpng(file)
current_size = File.size(file.path)
Paperclip.run("optipng", "-o7 --strip=all #{file.path}")
compressed_size = File.size(file.path)
compressed_ratio = (current_size - compressed_size) / current_size.to_f
logger.debug("#{current_size} - #{compressed_size} - #{compressed_ratio}")
logger.debug("PNG family compressed, compressed: #{ '%.2f' % (compressed_ratio * 100) }%")
end
end
Paperclip Only Showing Default Image
I just had to remove the @ from @user.image.url
Rails paperclip and upside down oriented images
Yes, this is a problem we solved last week where I work. :) If you're using ImageMagick/RMagic for image processing, you can use Image#auto_orient
to "rotate or flip the image based on the image's EXIF orientation tag"; call this method on the image in a Paperclip processor and you should be good to go.
[Edit]
You may be interested in Rails, Paperclip, -auto-orient, and resizing.... I also found it interesting that CarrierWave made this process very easy:
class ImageUploader < CarrierWave::Uploader::Base
... # config here
process :rotate
def rotate
manipulate! do |image|
image.auto_orient
end
end
end
Rails 4 Paperclip Images not uploading/showing (only missing.png)
After a little more research and a few cold drinks I found the solution!
It's necessary to either explicitly allow certain formats to get uploaded OR remove the verification check (I recommend this for development).
Doing this is as simple as adding the following line to your model (for me, entry.rb)
(SOURCE: https://stackoverflow.com/a/21898204/3686898)
do_not_validate_attachment_file_type :image
Also, I added another check in my controller (same as attr_accessible in earlier Rails versions):
private
# Use callbacks to share common setup or constraints between actions.
def set_entry
@entry = Entry.find(params[:id])
end
# Never trust parameters from the scary internet, only allow the white list through.
def entry_params
params.require(:entry).permit(:description, :image)
end
Alrighty, I hope this helps someone out :)
(Always remember to have a look at your server-logs. It provides golden information!)
Related Topics
Can't Dup Nilclass on Association Methods
How to Mix Required Argument and Optional Arguments in Ruby
Can't Access the Dockerized App Launched from the Command Line from Outside
Confused with Ruby Accessor Methods
How to Get the File Creation Time in Ruby on Windows
Why Should You Avoid the Then Keyword in Ruby
Which Global Variable Is for Last Expression
Ruby on Rails: Fully Functional Tableless Model
Why Do I Get "Undefined Method 'Paginate'" Error in Production
How to Read a Clients Windows Login Name Using Ruby on Rails
Testing HTML5 File Upload with Capybara/Selenium Webdriver - Ruby
Display Result Data Without Page Refresh on Form Submission in Ruby on Rails
P Method in Ruby Hard to Search For
Dangerousattributeerror in Omniauth Railscast Tutorial: Create Is Defined by Activerecord
Ruby CSV.Each in While Loop Not Executing Second Time Through