views:

30

answers:

2

What's the best way to generate Pictures, Pixel by Pixel in Ruby on Rails. I have a two-dimenisonal matrix with all the color values for each pixel, which i want to vizualize.

Something like this:

myBitmap = new Bitmap(:width => Column.all.count, :height => Row.all.count)
Colum.all.each do |col|
 Row.all.each do |row|
  #Draw the Pixel, with the color information in the matrix
 end
end 
+1  A: 

Not sure this is really a RoR but more a Ruby question. One way is to use RMagick, a wrapper around ImageMagick. RMagick is said to leak memory and it can be a pain to install Rmagick/Imagemagick. I had best experiences when installing Imagemagick with brew (OS X).

require 'rubygems'
require 'rmagick'
width = 100
height = 100
data = Array.new(width) do
  Array.new(height) do
    [rand(255), rand(255), rand(255)]
  end
end


img = Magick::Image.new(width, height)

data.each_with_index do |row, row_index|
  row.each_with_index do |item, column_index|
    #puts "setting #{row_index}/#{column_index} to #{item}"
    img.pixel_color(row_index, column_index, "rgb(#{item.join(', ')})")
  end
end

img.write('demo.bmp')
pascal betz
thx, great to see your answer, with rmagick it worked :)So for my Proof of Concept Code it's fine with the memory leaks...However rmagick isn't maintained any longer http://rubyforge.org/forum/forum.php?forum_id=38086 , so I'll keep searching for a better Image-Library to use in Ruby.
Silvermind
A: 

You could also use GD2 and it's ruby binding. Does not seem to be very popular though. Did not know about RMagick not beeing maintained anymore. Thanks.

require 'rubygems'
require 'gd2'

width = 100
height = 100
data = Array.new(width) do
  Array.new(height) do
    rand(16777216)
  end
end
image = GD2::Image::TrueColor.new(width, height)
data.each_with_index do |row, row_index|
  row.each_with_index do |item, column_index|
    image.set_pixel(row_index, column_index, item)
  end
end

File.open('gd2demo.png', 'wb') do |file|
  file << image.png
end
pascal betz