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

14

我正在为我们家庭局域网创建一个小型的照片分享网站,其中有一个上传功能,可以将原始大小的照片上传到数据库中。但是,我还想保存四种其他尺寸的照片:W=1024、W=512、W=256和W=128,但仅限于比原始尺寸小的尺寸(例如,如果原始宽度为511,则只生成256和128)。宽度为128的图像应始终生成(因为它是缩略图)。此外,调整大小应始终具有成比例的宽度和高度。我该如何实现这一点?

pic.rb <-- model

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 <-- 视图

<h1>New pic</h1>

<% form_for(@pic, :html => {:multipart => true}) do |f| %>
  <%= f.error_messages %>

  <p>
    <%= f.label :title %><br />
    <%= f.text_field :title %>
  </p>
  <p>
    <%= f.label :description %><br />
    <%= f.text_field :description %>
  </p>
  <p>
    <%= f.label :image_file %><br />
    <%= f.file_field :image_file %>
  </p>
  <p>
    <%= f.submit 'Create' %>
  </p>
<% end %>

<%= link_to 'Back', pics_path %>

谢谢

5个回答

26

您可以使用RMagick gem来调整大小。

这只是一个您可以适应的示例:

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


10

3
我尝试了以下方法。它正常工作。 我希望它能帮助到某些人。
1. 在Gemfile中添加以下gem:
gem "ImageResize", "~> 0.0.5"

2. 运行捆绑包 3. 在控制器函数中使用这个
require 'rubygems'
require 'ImageResize'

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

2

1

有一个叫做“Refile”的宝石,它非常棒。请查看这个教程,了解如何使用它。 https://gorails.com/episodes/file-uploads-with-refile 以下是如何操作。

将此代码添加到您的Gem文件中。

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

使用rails migration在你的表中创建一个名为image_id、类型为string的表字段。现在介绍如何向该字段插入数据并显示图片。
在上传表单中使用form_for do |f|。
 <%= f.attachment_field :image %>

如果您正在使用Rails 4,请确保传递Rails强参数。
将其放入存储图像的model.rb文件中(在modelname类下方)。
attachment :image

显示图片很简单。
<%= image_tag attachment_url(current_user,:image, :fill, 200, 170, format: "jpg") %>

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接