Get Instagram Image with C#

Instagram Baner

In this article we are going to learn how to get Instagram image with C# without using the Instagram API. Source code is provided at the end of the article.

How “Instagram Photo Downloader” app works

First let’s choose an image we want to download. In my case that would be an amazing photo by Peter McKinnon:

Peter McKinnon instagram profile
Image 1: Peter Mckinnon Instagram profile

Once we have chosen the photo, we need to retrieve the post url address:

https://www.instagram.com/p/CCGwk8MprRH/

Next we paste the address in the app, and choose where you would like to save the images:

Instagram Photo Downloader App Demo
Image 2: Instagram Photo Downloader

And just hit Download.

Images downloaded with the app
Image 3: Images downloaded

How to Get Instagram image with C#

First we need to download the web page source code from the Instagram post

public async Task<string> DownloadPostSourceCode(Uri webPageUri)
{
     using (WebClient client = new WebClient())
     {
          return await client.DownloadStringTaskAsync(webPageUri);
     }
}

In order to do that we are using WebClient class.

Next we want to find the URL from where we can actually download the photo. To do this we use a very simple regular expression:

"((""display_url"":""https://).*?(p1080x1080)?(oe=[A-Z0-9]{5,}""))"

Using this regular expression we are searching for a text that starts with: “display_url”:”https:// then it is followed by the text “p1080x1080” and ends with “oe={uppercase letter/number combination}”

Before the URL is usable we need to unescape the string. Inside the downloaded web page source the image URL contains escaped & “ampersand” character.

To unescape the string we can use Regex.Unescape(string)

Once we have the image URL we can extract the image file name with the following expression:

"[0-9]*_[0-9]*_[0-9]*_n.jpg"

Next, for every string matched by our expression we can download the image using the WebClient class again, only this time we are opening a readable stream for the data downloaded from a resource with the URI specified as a URI parameter.

using (WebClient webClient = new WebClient())
{
     using (Stream stream = webClient.OpenRead(imageUri))
     {
          return Image.FromStream(stream);
     }
}

As a result we can create an Image instance from the provided stream.

All we have to do now is save the image on our hard drive

image.Save({image_location});

By combining the chosen download directory with the extracted image file name.

Image Downloader App source code

The source code can be downloaded from the following link

More Tutorials

Leave a Reply

Your email address will not be published. Required fields are marked *

Back to Top