Ruby on Rails中的基本图像大小调整

我正在为我们家的内联网创建一个小照片共享网站,我有一个上传function,它将原始大小的照片上传到数据库中。 但是,我还想将照片保存为其他四种尺寸:W = 1024,W = 512,W = 256和W = 128,但只有小于原始尺寸的尺寸(例如,如果原始宽度为511,则仅生成256和128)。 应始终生成宽度为128的图像(因为它是缩略图)。 此外,重新调整应始终具有成比例的宽度和高度。 我该如何实现呢? 我已经有了上传照片的代码:

pic.rb < – 模型

def image_file=(input_data) self.filename = input_data.original_filename self.content_type = input_data.content_type.chomp self.binary_data = input_data.read # here it should generate the smaller sizes #+and save them to self.binary_data_1024, etc... end 

new.rb < – view

 

New pic

{:multipart => true}) do |f| %>




谢谢

只需使用paperclip或attachment_fu即可

您可以使用RMagick gemresize。

这只是一个你可以适应的例子:

 require 'RMagick' f = File.new( File.join(save_path, self.filename), "wb" ) f.write form_file.read #remeber to set :html=>{:multipart => true} in form f.close image = Magick::Image.read(self.filename).first image.change_geometry!("640x480") { |cols, rows, img| newimg = img.resize(cols, rows) newimg.write("newfilename.jpg") } 

更多信息: http : //www.imagemagick.org/script/api.php#ruby

我尝试了以下方式。 它的工作正常。 我希望它对某个人有所帮助。

1.在Gemfile中添加以下gem:

 gem "ImageResize", "~> 0.0.5" 

2.run捆绑

3.在控制器function中使用它:

 require 'rubygems' require 'ImageResize' #input_image_filename, output_image_filename, max_width, max_height Image.resize('big.jpg', 'small.jpg', 40, 40) 

知道这是一个旧的,但根据这个主题,这是一个非常好的railscast: http: //railscasts.com/episodes/253-carrierwave-file-uploads它正在使用rmagic和carrierwave。

有一种名为“Refile”的gem。 太棒了。 继续,查看本教程,了解如何使用它。 https://gorails.com/episodes/file-uploads-with-refile这里是如何做到的。

将其添加到您的gem文件中

 gem 'refile', '~> 0.4.2', require: ["refile/rails", "refile/image_processing"] 

在表中使用rails migration创建一个表字段作为字符串类型的image_id。现在如何插入该字段并显示图像。

在您的上传表单中使用它,主要是form_for do | f |

  <%= f.attachment_field :image %> 

如果您使用的是rails 4,请确保传递rails强参数。

将它放在存储图像的model.rb文件中(在类名称下面)

 attachment :image 

显示图像很简单。

 <%= image_tag attachment_url(current_user,:image, :fill, 200, 170, format: "jpg") %>