From 9ccc2e3dc08648469ff5383b35cc6a0929ec7ab6 Mon Sep 17 00:00:00 2001 From: Ola Tuvesson <196348+clickworkorange@users.noreply.github.com> Date: Wed, 24 Jan 2024 22:06:40 +0000 Subject: [PATCH] Added support for the "crop" method to the vips processor. --- lib/carrierwave/processing/vips.rb | 33 ++++++++++++++++++++++++++++++ spec/processing/vips_spec.rb | 9 ++++++++ 2 files changed, 42 insertions(+) diff --git a/lib/carrierwave/processing/vips.rb b/lib/carrierwave/processing/vips.rb index 52df75db4..5c7c618f1 100644 --- a/lib/carrierwave/processing/vips.rb +++ b/lib/carrierwave/processing/vips.rb @@ -78,6 +78,14 @@ def resize_to_fill(width, height, gravity='centre') def resize_and_pad(width, height, background=nil, gravity='centre', alpha=nil) process :resize_and_pad => [width, height, background, gravity, alpha] end + + def resize_to_fit(width, height) + process :resize_to_fit => [width, height] + end + + def crop(left, top, width, height) + process :crop => [left, top, width, height] + end end ## @@ -208,6 +216,31 @@ def resize_and_pad(width, height, background=nil, gravity='centre', alpha=nil, c end end + ## + # Crop the image to the contents of a box positioned at [left] and [top], with the dimensions given + # by [width] and [height]. + # + # + # === Parameters + # + # [left (integer)] left edge of area to extract + # [top (integer)] top edge of area to extract + # [width (Integer)] width of area to extract + # [height (Integer)] height of area to extract + # + # === Yields + # + # [Vips::Image] additional manipulations to perform + # + def crop(left, top, width, height, combine_options: {}) + width, height = resolve_dimensions(width, height) + + vips! do |builder| + builder.crop(left, top, width, height) + .apply(combine_options) + end + end + ## # Returns the width of the image in pixels. # diff --git a/spec/processing/vips_spec.rb b/spec/processing/vips_spec.rb index 97d99f72d..7c2eff7f5 100644 --- a/spec/processing/vips_spec.rb +++ b/spec/processing/vips_spec.rb @@ -188,6 +188,15 @@ end end + describe '#crop' do + it 'extracts an area defined from the left and top positions, with the given width and height' do + instance.crop(70, 40, 500, 400) + + expect(instance).to have_dimensions(500, 400) + expect(::Vips::Image.new_from_file(instance.current_path).get("vips-loader")).to match(/jpeg/) + end + end + describe "#width and #height" do it "returns the width and height of the image" do instance.resize_to_fill(200, 300)