use*_*917 1 image rmagick sinatra
目前我正在编写一个Sinatra应用程序,它从用户那里获取一些图片并返回一张新图片.
有一部分haml形式:
%input{type:'file', name:'user_image'}
Run Code Online (Sandbox Code Playgroud)
还有来自处理程序的代码:(蒙太奇是另一张图片)
source_userpic = params[:user_image][:tempfile]
blob = File.open(source_userpic).read
userpic = ImageList.new
userpic.from_blob(blob)
resized_img = userpic.scale(montage.columns,
montage.rows)
resized_img.opacity = MaxRGB/3
Run Code Online (Sandbox Code Playgroud)
然后两个图像"复合"并存储(不需要)
final_picture = ImageList.new
final_picture << montage.composite(resized_img, 0, 0, OverCompositeOp)
final_picture.write("./public/uploads/#{DateTime.now}.jpg" # dirty (for example)
Run Code Online (Sandbox Code Playgroud)
接下来,我需要使用ajax显示final_picture.有两个明显的问题:第一,我不需要保存final_picture - 它只是预览,第二,我必须编写代码以避免文件名冲突...
如何发送final_picture来查看?to_blob方法?但下一步是什么?
我通过使用数据URI方案解决了这个问题.
require 'base64'
final_picture.format = "jpeg" # whatever
# Using a to_blob method to create a direct-to-memory version of the image.
# Then encode it to base64 string
data_uri = Base64.encode64(final_picture.to_blob).gsub(/\n/, "")
@image_tag = '<img alt="preview" src="data:image/jpeg;base64,%s">' % data_uri
haml:'pages/preview'
Run Code Online (Sandbox Code Playgroud)
然后显示图片
= @image_tag
Run Code Online (Sandbox Code Playgroud)
不确定这是否是最好的解决方案