Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rmagick crop to same image?

I have find that when you want to crop an image in Rmagick, it doesn't mutate the current image object, but it returns a new one.

So, if I have:

@image = Magick::ImageList.new(path)
@cropped = @image.crop(10,10,20,20)

I wonder if the following code would be a good solution in terms of if I want to have always @image to contain the current image that is being manipulated.

@image = Magick::ImageList.new(path)
@image = @image.crop(10,10,20,20)

This works, but would I be having two images here? Should I destroy the first one before reassigning to @image?

like image 916
Hommer Smith Avatar asked Dec 07 '25 05:12

Hommer Smith


1 Answers

There is an in-place version of crop called crop!:

img.crop!(x, y, width, height) -> self
img.crop!(gravity, x, y, width, height) -> self
img.crop!(gravity, width, height) -> self

The in-place form of crop.

so you can say:

@image = Magick::ImageList.new(path).crop!(10,10,20,20)

if you want to avoid making a copy. Or you could let the GC deal with it and say:

@image = Magick::ImageList.new(path).crop(10,10,20,20) # No `!` here
like image 188
mu is too short Avatar answered Dec 08 '25 18:12

mu is too short



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!