我正在试图弄清楚如何让用户从他们的计算机上传照片或从Facebook获取照片。
我已经有了一个上传图片并使用Paperclip插件保存的表单。这很好。
我已经设置了Facebook身份验证,并使用Koala gem访问Facebook图形API。
我已经写过这个方法了:
def fetch_fb_picture
unless current_user.authentications.blank?
@graph = Koala::Facebook::GraphAPI.new(current_user.authentications.find_by_provider("facebook").token)
@picture = @graph.get_picture("#{current_user.authentications.find_by_provider('facebook').username}")
current_user.profile.photo = @picture
end
end
我相信Koala gem会返回图片的网址。但是,由于我使用的是paperclip gem,我的个人资料会接受这些属性:
t.string "photo_file_name"
t.string "photo_content_type"
t.integer "photo_file_size"
因此,如何将Facebook图像正确保存到数据库中?
答案 0 :(得分:6)
您可以执行以下操作:
r = open("http://graph.facebook.com/#{@user.facebook_id}/picture")
image_data = r.read
file_size = r.length
mime_type = "image/jpeg" #fb photos always are jpg
#write data to database, or save as temp file and upload to S3
我不建议这样做,因为Faceboook图将始终返回用户的图像,因为它们总是公开可用。您只需要在他们的ID或用户名之后调用/图片。你可以有一个布尔值来查看它是否是facebook用户,只需使用ID来显示图像。这也将确保您拥有最新的Facebook照片。
if @user.facebook_image?
image_tag "http://graph.facebook.com/#{@user.facebook_id}/picture"
else
image_tag @user.photo.url(:thumb)
end
答案 1 :(得分:2)
我正在寻找获取FB个人资料照片并使用rails将其保存到s3,我找到了一种基于之前答案的方法(使用rmagick):
r = open("http://graph.facebook.com/"+params[:FacebookId]+"/picture?width=142&height=142")
bytes = r.read
img = Magick::Image.from_blob(bytes).first
fmt = img.format
data=StringIO.new(bytes)
data.class.class_eval { attr_accessor :original_filename, :content_type }
data.original_filename = Time.now.to_i.to_s+"."+fmt
data.content_type='image.jpeg'
user.profilepic = data
user.save