How can I generate Bitmap Pictures in Ruby on Rails
What's the best way to generate Pictures, Pixel by Pixel in Ruby on Rails. I have a开发者_JAVA百科 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
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')
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
精彩评论