2012-07-11 122 views
6

我使用omniauth-twitter gem通過Twitter驗證用戶身份。我也使用他們的Twitter個人資料圖片作爲我的網站的頭像。但是,我從Twitter獲得的圖像是低分辨率。我知道Twitter有更好的分辨率照片。我如何得到它?從omniauth-twitter獲取中型或大型個人資料圖片

這是我目前正在做的。這是用戶模型中的一種方法。它的工作原理,只是沒有得到我的好品質圖片:

user.rb

def update_picture(omniauth) 
    self.picture = omniauth['info']['image'] 
    end 

我想也許我可以一個大小選項轉嫁到它在某種程度上,但似乎無法找到一個很好的解決方案。

回答

16

我正在使用omniauth-twitter gem。在我的用戶模型apply_omniauth方法,我保存這樣的Twitter圖片路徑,剝離_normal後綴:

if omniauth['provider'] == 'twitter' 
    self.image = omniauth['info']['image'].sub("_normal", "") 
end 

然後,我有所謂的肖像一個helper方法接受一個尺寸參數。至於特倫斯·伊登建議,您只需更換_size後綴的文件名來訪問the different image sizes that Twitter provides

def portrait(size) 

    # Twitter 
    # mini (24x24)                 
    # normal (48x48)            
    # bigger (73x73)             
    # original (variable width x variable height) 

    if self.image.include? "twimg" 

     # determine filetype   
     case 
     when self.image.downcase.include?(".jpeg") 
      filetype = ".jpeg" 
     when self.image.downcase.include?(".jpg") 
      filetype = ".jpg" 
     when self.image.downcase.include?(".gif") 
      filetype = ".gif" 
     when self.image.downcase.include?(".png") 
      filetype = ".png" 
     else 
      raise "Unable to read filetype of Twitter image for User ##{self.id}" 
     end 

     # return requested size 
     if size == "original" 
      return self.image 
     else 
      return self.image.gsub(filetype, "_#{size}#{filetype}") 
     end 

    end 

end 
+0

此答案給出了更詳細和有用的答案,以及用子方法去除「_normal」的解決方案。謝謝! – 2013-05-22 20:57:25

8

一旦你有了圖像的URL,它很簡單。您需要從網址末尾刪除「_normal」。

這裏是我的頭像圖片

https://si0.twimg.com/profile_images/2318692719/7182974111_ec8e1fb46f_s_normal.jpg 

這裏的放大版本

https://si0.twimg.com/profile_images/2318692719/7182974111_ec8e1fb46f_s.jpg 

一個簡單的正則表達式應該足夠了。

請記住,圖像的大小是不可預測的 - 所以你可能希望在顯示它之前調整它的大小。

+1

你失去了我在 「一個簡單的正則表達式」 :)我會嘗試一下。有關如何最好地將正則表達式添加到我擁有的方法的任何建議?謝謝。 – thatdankent 2012-07-11 17:20:48

+0

實際上,我沒有保存帶有修改的url,而是使用.sub方法將圖像加載到視圖中時修改了url:user.picture.sub(「normal」,「reasonably_small」) – thatdankent 2012-07-11 18:20:34

相關問題