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)
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With