Retrieve image dimensions

There are various ways to retrieve when using Carrierwave. They are as follows:

Using RMagick gem:

  class ImageUploader < CarrierWave::Uploader::Base
    include CarrierWave::MiniMagick
    process :store_dimensions
    private
      def store_dimensions
        if file && model
          model.width, model.height = ::MiniMagick::Image.open(file.file)[:dimensions]
        end
      end
  end

Using ImageMagick gem:

  class ImageUploader < CarrierWave::Uploader::Base
    include CarrierWave::MiniMagick
    process :store_dimensions
    private
      def store_dimensions
        if file && model
          model.width, model.height = ::MiniMagick::Image.open(file.file)[:dimensions]
        end
      end
  end

These are pretty good ways to retrieve image dimensions on server-side.

It would be much more easier if we could handle it on client-side (JQuery).
There could be many ways to do so. Below is the way I adopted in one of the project using FileReader API.

 $("input[type='file']").live 'change', (e) ->
    file = this.files[0]
    reader = new FileReader()
    img = new Image()
    reader.onload = (e) ->
      img.src = e.target.result
      img.onload = (e) ->
        console.log(this.width())
        console.log(this.height())

    reader.readAsDataURL(this.files[0]);

This worked in my case and I was able to restrict the image-size to some defined size.

Maybe it can help you as well.

References:

  1. [https://github.com/carrierwaveuploader/carrierwave/wiki/How-to:-Get-image-dimensions(Carrierwave)][1]
  2. [http://www.sitepoint.com/get-loaded-with-the-file-api/(Jquery FileReader API)][2]

    [1]: https://github.com/carrierwaveuploader/carrierwave/wiki/How-to:-Get-image-dimensions
    [2]: http://www.sitepoint.com/get-loaded-with-the-file-api/