Thursday, April 7, 2016

Saving Base64 String as image to Azure Blob Storage

 

Recently I started working on a API which supports mobile backend. I got the following requirement

1. When user uploads a image to their profile API will get the base64 string of the image

2. When viewing the User profile to increase the performance of service calls have to send an image URL rather base64 string

 

Solution : Save the base 64 string in the azure storage & save it in DB

  
  public class AzureBlogService
    {
        private static string _connectionString = "DefaultEndpointsProtocol=https;AccountName=****;AccountKey=****";
        public static string UploadImage(string imageData, ImageType imageType, int cardId)
        {
            string filename = GetFileName(imageType, cardId);
            CloudBlobContainer container = GetContainer("userimages");
            byte[] imageBytes = Convert.FromBase64String(imageData);
            CloudBlockBlob blob = container.GetBlockBlobReference(filename);
            blob.Properties.ContentType = "Jpeg";
            blob.UploadFromByteArray(imageBytes, 0, imageBytes.Length);
            return blob.StorageUri.PrimaryUri.AbsoluteUri;
        }

        private static CloudStorageAccount GetConnection()
        {
            CloudStorageAccount storageAccount = CloudStorageAccount.Parse(_connectionString);
            return storageAccount;
        }

        private static string GetFileName(ImageType imageType, int cardId)
        {
            switch (imageType)
            {
                case ImageType.Cover:
                    return string.Format("Cover-{0}.jpeg", cardId);
                case ImageType.Profile:
                    return string.Format("Profile-{0}.jpeg", cardId);
                default:
                    return null;
            }


        }
        private static CloudBlobContainer GetContainer(string containerName)
        {
            CloudStorageAccount storageAccount = GetConnection();
            // Create the blob client.
            CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient();

            // Retrieve a reference to a container.
            CloudBlobContainer container = blobClient.GetContainerReference(containerName);

            // Create the container if it doesn't already exist.
            container.CreateIfNotExists();

            return container;
        }


    }

Hope this is helpful.

Happy Coding !!!

No comments :

Post a Comment