Search code examples
javatwittertwitter4j

Retrieve exact image size using twitter4j


I have seen examples on retrieving images and their sizes but most give size variation (s) provided by Twitter.

One part of JSON source from twitter call has:

"media":[{"display_url":"pic.twitter.com/JLYolPIqvN","indices":[71,94],"sizes":{"small":{"w":340,"h":227,"resize":"fit"},"large":{"w":980,"h":653,"resize":"fit"},"thumb":{"w":150,"h":150,"resize":"crop"},"medium":{"w":600,"h":400,"resize":"fit"}}

This is what seems to be used in examples I have seen. But this doesn't give exact image size but available variations.

is it possible to get exact image size? e.g. if i wanted to only use medium image how do I get that?

Thanks.


Solution

  • You can to append the size to the end of the image URL.

    For example, let's take this Tweet - https://twitter.com/RGB_Colours/status/699202254407147520

    If we look at the entities, we will see the media_url_https which contains the URl of the image:

    media": [
          {
            "id": 699202254352621600,
            "id_str": "699202254352621568",
            "indices": [
              27,
              50
            ],
            "media_url": "http://pbs.twimg.com/media/CbQQvuzXIAA3cjd.png",
            "media_url_https": "https://pbs.twimg.com/media/CbQQvuzXIAA3cjd.png",
            "url": "https://t.co/FHNjU2c0SB",
            "display_url": "pic.twitter.com/FHNjU2c0SB",
            "expanded_url": "http://twitter.com/RGB_Colours/status/699202254407147520/photo/1",
    

    The image URL is https://pbs.twimg.com/media/CbQQvuzXIAA3cjd.png - so we can append :thumb, :small, :medium, :large to it:

    You can also use the (undocumented) parameter :orig which will give you the original size of the image. This may or may not be larger than :large