How to create bitmaps in Ruby on Rails

What is the best way to create images, Pixel by Pixel in Ruby on Rails. I have a two-dimensional matrix with all the color values ​​for each pixel that I want to render.

Something like that:

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 
+3
source share
2 answers

Not sure if this is really RoR, but more a Ruby question. One way is to use RMagick, a wrapper around ImageMagick. RMagick is reportedly leaking memory and it can be painful to install Rmagick / Imagemagick. I had the best experience 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')
+3
source

GD2 . , , . , RMagick . .

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
0

Source: https://habr.com/ru/post/1769645/


All Articles