Retrieving Medium or Large Profile Image from Twitter with omniauth-twitter

六眼飞鱼酱① 提交于 2019-12-02 19:47:48

I'm using the omniauth-twitter gem as well. In the apply_omniauth method of my User model, I save the Twitter image path like this, stripping the _normal suffix:

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

Then I have a helper method called portrait that accepts a size argument. As Terence Eden suggests, you can just replace the _size suffix of the filename to access 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

Once you have the URL of the image, it's quite simple. You need to remove the "_normal" from the end of the URL.

Here's my avatar image

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

Here's the larger version

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

A simple regex should suffice.

Remember, the size of the image is unpredictable - so you may wish to resize it before displaying it on your site.

A better way to do this is through the config options of the omniauth-twitter gem.

provider :twitter, "API_KEY", "API_SECRET", :image_size => 'original'

https://github.com/arunagw/omniauth-twitter

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!