如何使用CarrierWave生成视网膜(iPad)友好(渐进式或隔行扫描)jpeg图像?
有很多报道称Mobile Safari会对非常大的JPEG图像进行下采样,因此难以为新iPad推出适合视网膜的分辨率。
解决方案似乎是将JPEG编码为渐进/隔行扫描文件。 因此,我很好奇我如何使用CarrierWave插件和RMagick扩展来生成这种类型的文件。
谢谢!
你可以使用MiniMagick :
manipulate! do |img| img.strip img.combine_options do |c| c.quality "90" c.depth "8" c.interlace "plane" end img end
截至今天,您将需要carriewave的存储库版本,因为尚未发布options[:write]
支持。
所以在你的Gemfile中,使用以下内容:
gem 'carrierwave', :github => "jnicklas/carrierwave"
然后,在您的上传器中,您可以定义如下内容:
version :big do process :resize_to_limit => [1024, 1024] process :optimize end def optimize manipulate! do |img, index, options| options[:write] = { :quality => 90, # Change the quality to 90% :depth => 8, # Set the depth to 8 bits :interlace => "Magick::PlaneInterlace" # Add progressive support for JPEG } img.strip! # Remove profile data end end
有用的参考: http : //www.imagemagick.org/RMagick/doc/constants.html#InterlaceType
请享用!
我已经将一个解决方案打包为gemhttps://github.com/jhnvz/retina_rails
您需要做的是:
- 将
gem 'retina_rails'
添加到您的Gemfile中。 - 运行
bundle install
。 - 添加
//= require retina
到您的Javascript清单文件(通常在app / assets / javascripts / application.js中找到)。
Carrierwave
-
添加
include RetinaRails::CarrierWave
到您的上传器的底部class ExampleUploader < CarrierWave::Uploader::Base version :small do process :resize_to_fill => [30, 30] end include RetinaRails::CarrierWave end
回形针
-
添加
include RetinaRails::Paperclip
到您的上传器的底部class ExampleUploader < ActiveRecord::Base has_attached_file :image, :styles => { :original => ["800x800", :jpg], :big => ["125x125#", :jpg] } include RetinaRails::Paperclip end
gem会根据您在上传器中定义的版本自动生成视网膜版本(将@ 2x附加到文件名)。 js检查用户是否有视网膜显示,如果是,则将@ 2x附加到图像文件名。
我可以将图像编码为Progressive JPEG,对我的CarrierWave Uploader执行以下操作:
class ImageUploader < CarrierWave::Uploader::Base include CarrierWave::MiniMagick process :optimize #For the real image version :version_1 do # other processes process :optimize end version :version_2, from_version: :version_1 do # other processes process :optimize end version :version_3, from_version: :version_2 do # other processes process :optimize end def optimize manipulate! do |img| img.combine_options do |c| c.strip c.quality '100' c.depth '8' c.interlace 'Line' end img end end end
您必须将最后一个将图像转换为Progressive JPEG的过程放置,否则将无法转换。
然后,如果您已经上传了一些图像,并且想要“重新创建”它们。 想象一下你的模型是:
class Picture < ActiveRecord::Base mount_uploader :image, ImageUploader end
因此,您必须执行以下操作以重新创建版本:
Picture.order("id ASC").each do |p| p.image.recreate_versions! puts "#{p.id}, #{p.image.url}" end
我根据ID订购了图片,因为如果它在流程的中间失败,我会有ID,我可以继续使用该ID。 你可以做的另一件事是拯救任何exception,并在数组中保存失败的图片,如下所示:
errored = [] Picture.order("id ASC").each do |p| begin p.image.recreate_versions! rescue => e errored << p.id end puts "#{p.id}, #{p.image.url}" end
最后,要检查图像是否已转换为Progressive JPEG,并安装了ImageMagick,请在终端中键入以下内容:
identify -verbose PATH_TO_IMAGE | grep Interlace
如果图像是渐进式JPEG,则输出将是Interlace: JPEG
,如果不是Interlace: None