StanAngeloff / compass-magick

Dynamic image generation for Compass using ChunkyPNG/PhantomJS.
http://StanAngeloff.github.com/compass-magick/
Other
157 stars 4 forks source link

Crop image to size? #18

Closed heybenji closed 10 years ago

heybenji commented 10 years ago

Hey there,

This is a question. First, this is an amazing little piece of software. Thanks for making it. I'm hoping to use compass-magick to make responsive background images by cropping a full size image into a few different sizes and aspect ratios.

I've spent some time with your docs, but it seems to only crop relative to the edges of the canvas. Is there a way to take an image and crop it to a particular size, say 320x320?

Any help would be appreciated.

Benji

StanAngeloff commented 10 years ago

Thanks for having a look at compass-magick. What you are describing is indeed not implemented at this time. You can create a Ruby plug-in for it, though. Here is the boilerplate code to get you started:

module Compass::Magick
  module Plugins
    # Crop the {Canvas} to the given width/height.
    #
    # @param [Integer] width The width of the target canvas.
    # @param [Integer] height The height of the target canvas.
    #
    # @return {Command} A command which applies the crop to the canvas.
    def magick_crop_to(width, height)
      Compass::Magick::Utils.assert_type 'width', width, Sass::Script::Number
      Compass::Magick::Utils.assert_type 'height', height, Sass::Script::Number
      Command.new do |canvas|
        target_width = Compass::Magick::Utils.value_of(width, canvas.width, 0)
        target_height = Compass::Magick::Utils.value_of(height, canvas.height, 0)
        canvas.crop(0, 0, target_width, target_height)
      end
    end
  end
end

Create a file crop_to.rb and place it inside a plugins sub-directory inside the directory from which you invoke the compass command. Here is how it looks on my end:

/tmp/magick
├── config.rb
├── plugins
│   └── crop_to.rb
└── style.scss

You can also choose to install the plug-in globally in ~/.magick/plugins (create the path if missing).

You can then reference the new method in Sass using magick-crop-to(width, height).

For a list of all the operations you can perform on the canvas variable, have a look at ChunkyPNG::Canvas::Operations. You just have to remember to return a Canvas inside the Command.new block.

I hope this helps.