Skip to content

Instantly share code, notes, and snippets.

@jcupitt
Last active April 30, 2023 02:32
Show Gist options
  • Star 7 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save jcupitt/8939150 to your computer and use it in GitHub Desktop.
Save jcupitt/8939150 to your computer and use it in GitHub Desktop.
auto-crop in ruby-vips
#!/usr/bin/env ruby
# "trim" is nnow built in, so this is easy
require 'vips'
im = Vips::Image.new_from_file(ARGV[0])
left, top, width, height = im.find_trim
im = im.crop(left, top, width, height)
im.write_to_file(ARGV[1])
@Nakilon
Copy link

Nakilon commented Mar 14, 2019

Is it still working? Or is there now a vips command line operator instead of script to do this?

@dkam
Copy link

dkam commented Jun 14, 2020

Easier now:

#!/usr/bin/env ruby

require 'rubygems'
require 'vips'

im = Vips::Image.new_from_file(ARGV[0])

left, top, width, height = im.find_trim
im = im.extract_area(left, top, width, height)

im.write_to_file(ARGV[1])

@jcupitt
Copy link
Author

jcupitt commented Jun 14, 2020

Thanks @dkam, updated.

@danielb2
Copy link

danielb2 commented Apr 28, 2023

I can't get neither of these to work. is this still working for you? Using the image to test

Screen Shot 2023-04-28 at 13 20 30

@jcupitt
Copy link
Author

jcupitt commented Apr 29, 2023

It should work. Your test PNG image has a solid alpha, so find_trim cant see the edges.

Try:

#!/usr/bin/env ruby

require 'vips'

im = Vips::Image.new_from_file(ARGV[0])

left, top, width, height = im.find_trim background: 0
im = im.extract_area(left, top, width, height)

im.write_to_file(ARGV[1])

If I run:

$ vips flatten ~/pics/marble.png x.png
$ ./trim4.rb x.png y.png

I get:

y

@danielb2
Copy link

danielb2 commented Apr 30, 2023

thank you. hm. seems background: 0 did it. but the filesize is bigger after

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment