Dogbert
Dogbert

Reputation: 222398

Image Manipulation in Ruby

I'm looking for a way to load up an existing png image, and do a pixel by pixel manipulation of the values. Ideally, something like

image = Image.open('my.png')
image = image.map_each_rgb do |r, g, b|
  [r-12, g+2, b+30]
end
image.save('my.png')

I've looked into rmagick, but couldn't find a way to achieve this.

Are there any alternatives that would allow such image editing?

Upvotes: 1

Views: 3988

Answers (3)

Carma Tec
Carma Tec

Reputation: 41

Add gem rmagick for ruby or rmagick4j for jruby in your gem file. Using paperclip convert_options we can give options for background-color, border-color, quality, re-size, shadow etc., Image Crop : Is implemented using paperclip and jcrop We can directly call jcrop using id/class. Then we can get the new height and width.

$(function() { $(‘#cropbox’).Jcrop(); }); For default crop size $(function() { $(‘#cropbox’).Jcrop({ onChange: update_crop, onSelect: update_crop, setSelect: [0, 0, 500, 500], aspectRatio: 1 }); });

For Update Crop Size

function update_crop(coords) { $(‘#crop_x’).val(coords.x); $(‘#crop_y’).val(coords.y); $(‘#crop_w’).val(coords.w); $(‘#crop_h’).val(coords.h); }

Read full article here : http://www.railscarma.com/blog/technical-articles/image-manipulation/

Upvotes: 0

jcupitt
jcupitt

Reputation: 11210

Here's how to do what you want in ruby-vips:

require 'vips'
include VIPS

im = Image.new('/home/john/pics/shark.png')

# y = x.lin(a, b) calculates (y = x * a + b), ie. a linear transform
# you can pass a single constant for a and b, or an array of constants, in
# which case one element of the array is used for each channel

# see http://rubydoc.info/gems/ruby-vips/0.3.0/VIPS/Image#lin-instance_method

# subtract 12 from red, add 2 to green, add 30 to blue
im = im.lin [1, 1, 1], [-12, 2, 30]

im.write('out.png')

It's much faster than rmagick, uses much less memory, and has no (as far as I know) leaks. See:

http://www.vips.ecs.soton.ac.uk/index.php?title=Speed_and_Memory_Use

Upvotes: 2

jrdioko
jrdioko

Reputation: 33525

How about RMagick's each_pixel method?

http://studio.imagemagick.org/RMagick/doc/image2.html#each_pixel

img.each_pixel {|pixel, c, r| block }

Upvotes: 3

Related Questions