从 Magick::Image 创建 ruby File 对象
我正在尝试使用 rmagick 和rest-client 将带水印的图像发布到网址。当我生成合成图像时,我将其保存 (.write),使用 File.new 将其读回,然后发布该 File 对象。但理想情况下,我想绕过写入操作,因为我再也不需要这张照片了。有什么方法可以将 Magick::Image 对象转换为 File 对象,以便我可以使用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'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)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我终于使用 StringIO 和 Koala gem(Facebook API 的 ruby 包装器)弄清楚了。代码如下所示:
关键是调用 Magick::Image 上的 to_blob,然后从该字符串创建 StringIO。当前版本的 Koala gem 有一个 StringIO 故障,但我已在我的 fork 中修复了它并提交了拉取请求:
https://github.com/arsduo/koala/pull/122
I finally figured it out using StringIO and the Koala gem (ruby wrapper for the Facebook API). The code looks like this:
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