Search code examples
ruby-on-rails-3twitteromniauthtwitter-oauth

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


I'm using omniauth-twitter gem to authenticate users through twitter. I am also using their Twitter profile image as their avatar for my site. However, the image I get from Twitter is low resolution. I know Twitter has better resolution pics available. How do I get it?

Here is what I am currently doing. It is a method in the user model. It works, just doesn't get me a good quality pic:

user.rb

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

I thought maybe I could pass a size option onto it somehow, but can not seem to find a good solution.


Solution

  • 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