Skip to content

Instantly share code, notes, and snippets.

@cp
Created January 15, 2025 18:59
Show Gist options
  • Save cp/bef6bdbc34641f06f612a4f13452dfc0 to your computer and use it in GitHub Desktop.
Save cp/bef6bdbc34641f06f612a4f13452dfc0 to your computer and use it in GitHub Desktop.
require "rmagick"
crop = [
0.46558651328086853, # x1 (proportion from left)
0.471098929643631, # x2 (proportion from left)
0.5287885069847107, # y1 (proportion from top)
0.5272343754768372, # y2 (proportion from top)
]
input_path = "./input.jpeg"
begin
image = Magick::Image.read(input_path).first
width = image.columns
height = image.rows
# Convert normalized coordinates to absolute pixels
x = (width * crop[0]).round
crop_width = (width * (crop[1] - crop[0])).round # x2 - x1
y = (height * crop[2]).round
crop_height = (height * (crop[3] - crop[2])).round # y2 - y1
cropped_image = image.crop(x, y, crop_width, crop_height)
cropped_image.write("output.jpeg")
rescue Magick::ImageMagickError => e
puts "Error processing image: #{e.message}"
rescue StandardError => e
puts "Error: #{e.message}"
ensure
image&.destroy!
cropped_image&.destroy!
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment