There are several reasons why you’ll want to host publicly accessible images yourself. For example, you may want to compress them or apply metadata for querying purposes on your site. For my Blast Off with Blazor project, I had that exact need.

In my case, I want to host images cheaply and also work with the image’s metadata over a NoSQL database. Azure Storage blobs and Azure Cosmos DB were obvious choices, since I’m already deploying the site as an Azure Static Web App.

To accomplish this, I wrote a quick Azure Function that accomplishes both tasks. Let’s take a look at how this works.

Before you begin: create Azure resources

Before you begin, you need to set up the following:

Once I created all these resources, I added the configuration values to my local.settings.json file. These values are available in the portal when you browse to your various resources. (When you deploy your resources, they’ll need to be added to your configuration.)

{
  "Values": {
    "ApiKey": "my-nasa-api-key",
    "CosmosEndpoint": "url-to-my-cosmos-endpoint",
    "CosmosKey": "my-cosmos-primary-key",
    "CosmosDatabase": "name-of-my-cosmos-db",
    "CosmosContainer": "name-of-my-cosmos-container",
    "StorageAccount": "storage-account-name",
    "StorageKey": "storage-key",
    "BlobContainerUrl": "url-to-my-container"
  }
}

The Azure function

In my Azure function I’m doing three things:

  • Call the NASA Image of the Day API to get a response with image details—including URL, title, description, and so on
  • From the URL in the response payload, copy the image to Azure Storage
  • Then, update Cosmos DB with the URL of the new resource, and the other properties in the object

If we look at the Astronomy Picture of the Day site, it hosts an image and its metadata for the current day. I want to put the image in Storage Blobs and the details in Cosmos DB.

#azure functions #azure storage blobs #cosmos db

Use Azure Functions, Azure Storage blobs, and Cosmos DB to copy images from public URLs
1.55 GEEK