Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

creating a ruby File object from Magick::Image

I'm trying to post watermarked images to a url using rmagick and rest-client. When I generate the composite image, I save it (.write), read it back in with File.new, and then post that File object. Ideally though, I'd like to bypass the write operation because I'll never need this photo again. Is there any way to convert a Magick::Image object into a File object so that I can post it with rest-client?

require 'rmagick'
require 'rest-client'

photo = Magick::Image.read('myphoto.jpg').first
water_mark = Magick::Image.read('watermark.png').first

result = photo.composite(water_mark, 0, 0, Magick::OverCompositeOp)
result.write('result.jpg')

file = File.new('result.jpg', 'rb')
RestClient.post("http://example.com", :source => file)
like image 770
john h. Avatar asked Jun 14 '11 05:06

john h.


Video Answer


1 Answers

I finally figured it out using StringIO and the Koala gem (ruby wrapper for the Facebook API). The code looks like this:

access_token = "asdfasdfasdfasdf"
graph = Koala::Facebook::API.new(access_token)
photo = Magick::Image.read("my_photo.jpg").first
watermark = Magick::Image.read("watermark.png").first
watermarked = photo.composite(watermark, 5, 5, Magick::OverCompositeOp)
photo_graph_id = StringIO.open(watermarked.to_blob) do |strio|
  response = graph.put_picture(strio, "image/jpeg", { "message" => "hi" })
  response['id']
end

The key was to call to_blob on the Magick::Image and then create a StringIO from that string. The current version of the Koala gem has a glitch with StringIO but I've fixed it in my fork and have submitted a pull request:

https://github.com/arsduo/koala/pull/122

like image 157
john h. Avatar answered Sep 19 '22 01:09

john h.