How can I retrieve image width and height #757

Closed
HungYuHei opened this Issue Jun 11, 2012 · 6 comments

Comments

Projects
None yet
4 participants

I need the ability to handle the different process according to image's dimensions.

Like this:

  version :normal do
    process :scale_image
  end

  def scale_image
    width = *THE_WAY_TO_GET_WIDTH*
    height = *THE_WAY_TO_GET_HEIGHT*

    if width && height && width > height
      process :resize_to_fit => [224, 320, '#000']
    else
      process :resize_to_fill => [224, 320, '#000']
    end
  end

So, my question is, how can I implement THE_WAY_TO_GET_WIDTH and THE_WAY_TO_GET_HEIGHT ?

With MiniMagick, you can get your image width and height using something like:

class MyUploader < CarrierWave::Uploader::Base
  include CarrierWave::MiniMagick

  def image_properties
   image_name = Rails.root.join("app", "assets", "images", "icons-s8098ac90c8.png")
   image = MiniMagick::Image.open(image_name)
   puts "width: #{ image[:width] }", "height: #{ image[:height] }"  # this line will retrieve what you need
  end 
end 

u = MyUploader.new
u.image_properties

If you want to use MiniMagick, don't forget to add it do your Gemfile. You can find more here: https://github.com/probablycorey/mini_magick

@cristiansorinel

I am sorry, I forgot to mention one thing: The image I want is from the one my user just uploaded

Add the following lines to your uploader file

  include CarrierWave::MiniMagick

  def image
    @image ||= MiniMagick::Image.open( model.send(mounted_as).path )
  end

  def image_width 
     image[:width]
  end

  def image_height
    image[:height]
  end

After adding those lines of code you can do something like this:

def scale_image
  width = image_width #function defined above
  height = image_height #function defined above

  if width && height && width > height
    process :resize_to_fit => [224, 320, '#000']
  else
    process :resize_to_fill => [224, 320, '#000']
  end
end
Contributor

trevorturk commented Jun 13, 2012

This would make great material for the wiki!

@trevorturk trevorturk closed this Jun 13, 2012

@cristiansorinel Much appreciated

adding to what @cristiansorinel mentioned

def image
   // this will provide height and width to any version of the image, like thumb, medium sizes
   // just do model.medium.image_width ...
   @image ||= MiniMagick::Image.open( file.file )
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment