Get image sizes with Refile

Using the Refile gem to handle file uploads in Rails, what is the best way to determine the height and width of the image during / after it was uploaded? There is no built-in support in this AFAIK, and I cannot figure out how to do this using MiniMagick.

+4
source share
3 answers
Comment

@russellb almost got me, but not quite right. If you have a Refile :: File called @file, you need to:

fileIO = @file.to_io.to_io
mm = MiniMagick::Image.open(fileIO)
mm.width # image width
mm.height # image height

Yes, two calls to #to_io> ... <The first to_io gives you a Tempfile, which MiniMagick does not want. Hope this helps someone!

- update -

: , (< ~ 20kb, from: ruby-forum.com/topic/106583), to_io, StringIO. , StringIO :

mm = MiniMagick::Image.read(fileio.read)

, :

# usually this is a Tempfile; but if the image is small, it will be 
# a StringIO instead >:[
fileio = file.to_io

if fileio.is_a?(StringIO)
  mm = MiniMagick::Image.read(fileio.read)
else
  file = fileio.to_io
  mm = MiniMagick::Image.open(file)
end
+8

reffile to_io (. Refile:: File docs), -, MiniMagick.

, file (, file_id) width height, :

class Image < ActiveRecord::Base

  attachment :file

  before_save :set_dimensions, if: :file_id_changed?

  def set_dimensions
    image = MiniMagick::Image.open(file.to_io)
    self.width = image.width
    self.height = image.height
  end

end

, .

+2

MiniMagick ( ).

image = MiniMagick::Image.open('my_image.jpg')
image.height #=> 300
image.width  #=> 1300

This is all well documented in README.md for the gem: https://github.com/minimagick/minimagick

0
source

Source: https://habr.com/ru/post/1629809/


All Articles