Ruby RMagick resizing images stored as binary data in a database

745 views Asked by At

So i have been using the Rmagick library for resizing images in ruby like so

require 'RMagick'
image = Magick::Image.read(filename).first
image.change_geometry!("640x480") { |cols, rows, img|
    newimg = img.resize(cols, rows)
    newimg.write("newfilename.jpg")
}

And this works just fine for an image stored in a file, but how do i do the same thing for images stored in a database just as binary data, so basically binary data in a variable.

1

There are 1 answers

0
mu is too short On BEST ANSWER

Magick::Image.read is little more than a short cut for opening a file, reading the data, and then converting that data to an array of images. If the data is in a database (presumably in a blob column of some sort) then you simply have to read the data from the database using whatever database interface you're using, then use from_blob to parse the data into a Magick::Image, resize it as usual, use to_blob to get the raw data back, and write that blob to the database as usual:

image = Magick::Image.from_blob(raw_binary_data_from_your_database).first
image.change_geometry!('640x480') do |cols, rows, img|
  newimg = img.resize(cols, rows)
  write_bytes_to_database(newimg.to_blob)
end

I don't know how you're accessing the database so the raw_binary_from_your_database variable and write_bytes_to_database method are placeholders for things that you have presumably already figured out.