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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With